菜单问题
在涉及到菜单管理的时候,从数据库拿到的数据都是平行的,都是相同的一条一条的记录,拿到的数据并没有分级,显然这些数据是需要处理的,处理成分组分级别的菜单。用笨办法来完成这项工作可以分为以下几步:
一、先从数据库拿到‘pid’为0的数据:
$menus = DB::table('xpcms_admin_menu')
->where(['status'=>0,'ishidden'=>0,'pid'=>0])->cates('mid');
二、遍历$menus
foreach ($menus as $key => $menu){
//从数据库中拿到'pid'为>$menu['mid']的数据
$children = DB::table('xpcms_admin_menu')
->where(['status'=>0,'ishidden'=>0,'pid'=>$menu['mid']])->cates('mid');
//然后把$children放入$menus[$key]['children']数组当中,得到二级分类;
$menus[$key]['children'] = $children;
三、再对$children进行遍历,得到三级菜单
foreach ($children as $k => $child){
$ch = DB::table('xpcms_admin_menu') ->where(['status'=>0,'ishidden'=>0,'pid'=>$child['mid']])->cates('mid');
$menus[$key]['children'][$k]['children'] = $ch;
}
完整代码
$menus = DB::table('xpcms_admin_menu')
->where(['status'=>0,'ishidden'=>0,'pid'=>0])->cates('mid');
foreach ($menus as $key => $menu){
$children = DB::table('xpcms_admin_menu') ->where(['status'=>0,'ishidden'=>0,'pid'=>$menu['mid']])->cates('mid');
$menus[$key]['children'] = $children;
foreach ($children as $k => $child){
$ch = DB::table('xpcms_admin_menu') ->where(['status'=>0,'ishidden'=>0,'pid'=>$child['mid']])->cates('mid');
$menus[$key]['children'][$k]['children'] = $ch;
}
}
结果
前端三级循环代码 <dl class="permission-list">
@foreach($menus as $menu)
<dt>
<label>
<input type="checkbox" value="{{$menu['mid']}}" name="menu[{{$menu['mid']}}]" id="user-Character-0">
{{$menu['title']}}</label>
</dt>
<dd>
@if(isset($menu['children']) && $menu['children'])
<dl class="cl permission-list2">
@foreach($menu['children'] as $children)
<dt>
<label class="">
<input type="checkbox" value="{{$children['mid']}}" name="menu[{{$children['mid']}}]" id="user-Character-0-0">
{{$children['title']}}</label>
</dt>
@if(isset($children['children']) && $children['children'])
@foreach($children['children'] as $child)
<dd>
<label class="">
<input type="checkbox" value="{{$child['mid']}}" name="menu[{{$child['mid']}}]" id="user-Character-0-0-0">
{{$child['title']}}</label>
</dd>
@endforeach
@endif
@endforeach
</dl>
@endif
</dd>
@endforeach
</dl>
前端渲染结果
这是创建管理权限组时的选项菜单,并不是真正的菜单,要想变成真正的菜单,还要将多级菜单处理成二级菜单。
需要特别注意的是
第二次遍历的时候,费了一些周折,一开始按照第一次遍历的思路,写成了foreach ($menus[$key][‘children’] as $k => $child){},一直得不到想要的结果,各种想,最终还算是碰对了。也算幸运,但是这是一种没有基础的人的笨办法,不值得推荐,也不需要采用,只是记录了我的一些摸索。