php Laravel以非递归方式迭代无限层次树视图

q0qdq0h2  于 2022-10-30  发布在  PHP
关注(0)|答案(1)|浏览(127)

我已经实现了将一个类别树递归地打印到页面上:

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) {
            if(count($arr->childs)){
            $html .='<li>'.$arr->title.'';                  
                    $html.= $this->childView($arr);
                }else{
                    $html .='<li>'.$arr->title.'';                                 
                    $html .="</li>";
                }                   
        }

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

对于DB结构:id|title|parent_id现在我需要实现一种迭代的方式来将一个类别树打印到页面上,到目前为止我还没有找到解决方案。
我也试探着:

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);

但是我也不知道如何非递归地使用这些数据。
有人能引导我走上正确的道路吗?也许我应该把foreach循环和某种while条件结合起来?

8fq7wneg

8fq7wneg1#

在您的类别模型中:

public function subCategories()
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}

public function children()
{
    return $this->subCategories()->with('children');
}

在您的模型中:

public function getCategories()
    {
        $categories = Category::whereNull('parent_id')->with('children')->get();

        return view('category', ['categories' => $categories]);
    }

刀片服务器(category.blade.php)

<div class="tree">
      @include('category-list-widget',['categories' => $categories])
</div>

blade.php中的一个页面

<ul>
   @foreach($categories as $category)
   <li>
      <a>{{$category->name}}</a>
      @if(!empty($category->children) && $category->children->count())
      @include('category-list-widget',['categories' => $category->children])
      @endif
   </li>
   @endforeach
</ul>

我没有测试代码,只是直接写在这里的texteditor.我希望你明白的想法.

相关问题