0

I'm trying to print list of categories with indefinite subcategories.

Example:

    [
        [
            'categoryName' => 'Category1',
            'categoryUrl' => 'category-1',
            'subcategories' => [
                [
                    'categoryName' => 'Subcategory 1',
                    'categoryUrl' => 'sucbategory-1',
                    'subcategories' => [
                        [
                            'categoryName' => 'Subcategory subcategory 1',
                            'categoryUrl' => 'sucbategory-subcategory-1',
                            'subcategories' => [
                                [
                                    '....'
                                ]
                            ]
                        ]
                    ],
                    [
                        'categoryName' => 'Subcategory 2',
                        'categoryUrl' => 'sucbategory-12',
                    ]
                ]
            ]
        ]
    ]

I was trying it with foreach inside foreach, etc... Then I realised I don't know how many levels category tree will have.

Category1->Subcategory1->Subcategory Subcategory1-> Subcategory ... 1-> ??

2

2 Answers 2

0

This is called a recursion. The idea is like this:

function printLeafs($node){
  echo $node->title;

  $leafs = getLeafs($node);
  foreach ($leafs as $leaf){
    printLeafs($leaf);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

This will print all using recursion.

function recurse($array) {

    foreach( $array as $one ) {
       echo $one['categoryName'] . '->' ;
       echo $one['categoryUrl'] . '->' ;

       if( isset($one['subcategories']) ) {
        if( is_array($one['subcategories'])) {
           recurse($one['subcategories']) ;
       }


       }
    }
};

recurse($array);

But in your code I've noted a problem, the following looks misplaced. In this case you are having categoryName not having a parent subcategories. If that a typo the above will work. Otherwise it wont.

'categoryName' => 'Subcategory 2',
'categoryUrl' => 'sucbategory-12',

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.