我实现了在Laravel中构建一个递归菜单,如下所示: picture of menustructure
我从模型向视图返回一个具有所有类别的对象($ categories)。每个类别都有一个ID | NAME | PARENT_ID
此刻,我正在努力获取元素的最后一个子类别以使其可单击。 如您在图片中看到的,“ Objektive ____ TEST ID:42 PARENT ID:24”应该是可单击的。
Laravel视图中的代码:
<?php
//Recursive function which returns all categories.
function output($categories,$id,$eltern)
{
//Output categories as <li> tag
?>
<ul class="list-unstyled components" >
<li > {{ $eltern->Name }} ID:{{$eltern->id}} PARENT ID: {{$eltern->parent_ID}} </li>
<?php
//compare the parent id with id of the previous categories
foreach ($categories as $key => $k){
if ($k->parent_ID == $id){
unset($categories[$key]);
//recursion
output($categories,$k->id,$k);
}
}
echo "</ul>";
}
?>
<nav id="sidebar">
<?php
//Main foreach which starts recursion
foreach($categories as $k){
if($k->parent_ID == 0){
output($categories,$k->id,$k);
}
}
?>
</nav>