amrsubzero's avatar

How to display Categories as Tree hierarchical

I want to display the categories like this example :

N|Categories

So if a parent category have child .. display like :

Cars
Cars => Accessories
Electronics
Electronics => Laptop
Electronics => Laptop => Batteries
extra...

i have categories table which has parent_id column and every category can have a parent_id from it's parent category.

and of course i have a Model Category and Controller CategoryController

How can i achieve this?

Thanks

0 likes
6 replies
bugsysha's avatar
bugsysha
Best Answer
Level 61

Just plain recursive call should be sufficient here.

function printCategoryName($categories, $parentName = '') {
    foreach ($categories as $category) {
        $name = $parentName ? implode(' > ', [$parentName, $category->name]) : $category->name;
        echo sprintf('%s%s', $name, PHP_EOL);

        if (count($category->children) > 0) {
            printCategoryName($category->children, $name);
        }
    }
}

printCategoryName($categories);
1 like
amrsubzero's avatar

@bugsysha the method works, but the childs outputting twice like :

N|issue

i mean it does output like : Electronics > Laptop but it also outputs like a parent category.

How can i solve this?

bugsysha's avatar

@amrsubzero then you are probably fetching all categories. Try fetching all categories which do not have parent_id.

1 like

Please or to participate in this conversation.