1 year ago

Laravel Iterate through unlimited hierarchy treeview non-recursively

Posted 1 year ago by ntel

I have constructed recursive way for printing a categories tree to the page:

    foreach ($categories as $category) {
         $tree .='<li>'.$category->title.'';
         if(count($category->childs)) {
            $tree .=$this->childView($category);
    $tree .='<ul>';

    return view('categoryTreeview',compact('categories','allCategories','tree'));

public function childView($category){                 
        $html ='<ul>';
        foreach ($category->childs as $arr) {
            $html .='<li>'.$arr->title.'';                  
                    $html.= $this->childView($arr);
                    $html .='<li>'.$arr->title.'';                                 
                    $html .="</li>";

        $html .="</ul>";
        return $html;

for DB structure: id|title|parent_id

and now i need to implement a Iterative way to print a category tree to the page, and so far i have not found a solution. I also tried:

function buildTree($categories) {

$childs = array();

foreach($categories as $category)
    $childs[$category->parent_id][] = $category;

foreach($categories as $category) if (isset($childs[$category->id]))
    $category->childs = $childs[$category->id];

 return $childs[0];
} $treez = buildTree($categories);

but also i don't have idea how to use this data non-recursively.

So my question is: Could anyone lead me on the right path? maybe i should combine foreach loops with some kind of while condition?

Please sign in or create an account to participate in this conversation.