Laravel 5.5递归函数创建菜单

时间:2018-05-17 13:06:07

标签: laravel laravel-5

我创建了一个mysql表,如下所示:

id | menuname          | parentid
---+-------------------+---------
 1 | dashboard         |        0
 2 | Content           |        0
 3 | Home Page Content |        2
 4 | Banners           |        2
 5 | Settings          |        0
 6 | Block Content     |        3
 7 | Site Content      |        3

这样菜单结构将如下所示:

  • 仪表板
  • 内容
    • 主页内容
      • 阻止内容
      • 网站内容
  • 横幅
  • 设置

我有控制器:

public function index() {
    $data = array();

    $permissionRecord = Permission::all();
    $this->categoryTree($permissionRecord);

    dd('-end-);
    $data['permissionRecord'] = $permissionRecord;

    return view('Administrator.permission.permissionAdd',$data);
}

function categoryTree($permissionRecord, $parent_id = 0, $sub_mark = '')
{
    foreach($permissionRecord as $row) {
        echo $sub_mark.$row->name;

        $this->categoryTree($permissionRecord, $row->id, $sub_mark.'---');
    }
}

但是这显示了数据:

  

控制板--- ------控制板控制板---------控制板------------ ------------控制板---仪表盘仪表盘------------------ ---------------------仪表板----- -------------------仪表板--------------------------- Dashboard-- - - - - - - - - - - - - - - 仪表板 - - - - - - - - - - - ------------仪表盘仪表盘------------------------------------

请注意,我在控制器内部dd()并没有将数据传递给视图。

1 个答案:

答案 0 :(得分:1)

您没有考虑父ID:

function categoryTree($permissionRecord, $parent_id = 0, $sub_mark = '')
{
    foreach($permissionRecord as $row) {
        if ($row->parentid == $parent_id) {
            echo $sub_mark.$row->name;

            $this->categoryTree($permissionRecord, $row->id, $sub_mark.'---');
        }
    }
}

试试看看会发生什么 - 注意我已经在if()中包装了递归函数调用,它检查当前记录parentId是否等于传递给方法的父ID。

要使其显示缩进列表中的项目:

public function categoryTree($permissionRecord, $parent_id = 0)
{
    $html = '<ul>';

    foreach($permissionRecord as $row) {
        if ($row->parentid == $parent_id) {
            $html .= '<li>' . $row->menuname;

            $html .= $this->categoryTree($permissionRecord, $row->id, $html);

            $html .= '</li>';
        }
    }

    $html .= '</ul>';

    return $html;
}

然后打电话:

$html = $this->categoryTree($permissionRecord);

使用单元测试的示例