0

I have a PHP array of categories like this

$category = array(
    1 => array(
        'id' => 1,
        'parentID' => 0,
        'name' => 'SUV auto parts'
    ),
        2 => array(
            'id' => 2,
            'parentID' => 1,
            'name' => 'Engine Related'
        ),
            3 => array(
                'id' => 3,
                'parentID' => 2,
                'name' => 'Spark Plugs'
                        ),
            4 => array(
                'id' => 4,
                'parentID' => 2,
                'name' => 'Engine Oil'
                        ),
        5 => array(
            'id' => 5,
            'parentID' => 1,
            'name' => 'Body related'
        ),
    6 => array(
        'id' => 6,
        'parentID' => 0,
        'name' => 'Sedan auto parts'
    ),
        7 => array(
            'id' => 7,
            'parentID' => 6,
            'name' => 'Engine Related'
            ),
        );

I have no idea how to get this done just by using PHP array without MYSQL query, trying to display sub-categories where 'parentID' = supplied category ID

for example when category id 1 is requested, I wanna list name and html link for category 2 and 5, when category id 2 is requested, I wanna display name and html link for category 3 and 4


SUV auto parts

Sub-categories; Spark Plugs Engine Oil


likewise when "Engine Related" page is requested


Engine Related

Sub-categories; Engine Related Body related


I appreciate if someone will give any solution.

1
  • 2
    So iterate over your array and find records that you need. What's the exact problem? Commented Jan 11, 2020 at 12:31

1 Answer 1

1

More sophisticated approaches exist surely, but a solution that is easy to understand and tailor(e.g. prettify) to your use case, is the following:

$parentId = 2; // set the parentID

foreach($category as $key => $value) {
    if($value['parentID'] == $parentId) {
        echo '<pre>';
        print_r($value); // print matching record
        echo '</pre>';
    }
}

working demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.