Laravel以非递归方式遍历无限层次结构树视图



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

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

对于数据库结构: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条件结合起来?

在您的类别模型中:

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

刀片(类别.刀片.php(

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

Blade (category-list-widget.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>

我没有测试代码,只是直接在文本编辑器中编写了它。我希望你明白这个想法。

最新更新