Skip to content

Get 3 or more level categories in magento2

i’m getting the sub category for the below code,but still i want more categories which mean it has sub categories of more levels how can i get this.

 foreach($categories as $category) {

            $cat = $this->getCategoryModel()->load($category->getId());
            $array[$category->getLevel()][$cat->getId()]= array('id' => $cat->getId(), 'level' => $cat->getLevel(), 'name' => $cat->getName(), 'url' => $cat->getUrl(), 'display_mode' => $cat->getDisplayMode(), 'image' => $cat->getImageUrl('wizard_icon'), 'description' => $cat->getWizardQuestion(), 'categories' => [] ); //In this line we get an a link for the product and product count of that category
            if($category->hasChildren()) {  //if category has children or not. If yes then it proceed in inside loop.
                 $children = $category->getChildrenCategories(); // $children get a list of all subcategories
                $array[$category->getLevel()][$cat->getId()]['categories']=  $this->get_categories($children); //recursive call the get_categories function again.
                }

        }
    return  $array;