php - 创建多级菜单 php Laravel
问题描述
我正在做在 laravel 中创建动态菜单的功能,我有如下 tbl_menu 表:
menu_id parent_id menu_name link order
1 0 Level_1 url_1 1
2 0 Level_1 url_2 1
3 2 Level_2 url_3 2
4 2 Level_2 url_4 3
5 4 Level_3 url_5 3
我希望结果是一个如下所示的数组:
-Level_1
-Level_2
-Level_2
-Level_1
_Level_2
_Level_2
_Level_3
我的代码如下:
public function SelectAllChildeLv1ByParentId($id){
$result = DB::table('tbl_menu')->where('parent_id', $id)
->orderBy('order', 'asc')->get();
return $result;
}
public function SelectAllMenuParent(){
$result = DB::table('tbl_menu')->where('parent_id', 0)
->orderBy('order', 'asc')->get();
return $result;
}
public function getMenuChildren($listParent, $step = 3)
{
$results = [];
if ($step > 0) {
$step--;
if($listParent) {
foreach($listParent as $index => $parent) {
$listChild = $this->SelectAllChildeLv1ByParentId($parent->menu_id);
$listChild1 = $this->getMenuChildren($listChild, $step);
$results[$index] = $parent;
$results[$index]->menu_child = $listChild1;
}
}
}
return $results;
}
public function getAllMenus() {
$allMenuParent = $this->SelectAllMenuParent();
$results = $this->getMenuChildren($allMenuParent);
return $results;
}
结果是正确的,但运行的查询太多。我想优化它,但还没有弄清楚。谢谢你的帮助。
解决方案
尝试 :
public function get()
{
$menu = DB::table('tbl_menu')
->orderBy('order', 'asc')->get();
$parents = $menu->where('parent', 0);
$items = self::tree($parents, $menu);
return $items;
}
public function tree($items, $all_items)
{
$data_arr = array();
foreach ($items as $i => $item) {
$data_arr[$i] = $item->toArray(); //all column attributes
$find = $all_items->where('parent', $item->id);
//$data_arr[$i]['tree'] = array(); empty array or remove if you dont need it
if ($find->count()) {
$data_arr[$i]['tree'] = self::tree($find, $all_items);
}
}
return $data_arr;
}
推荐阅读
- ios - UITextView 中的 UITextField 函数不可用
- python - 从 Selenium 导入元素时,会写入 CSV 上的多行而不是一行
- kotlin - 如何在 Kotlin 中分配当前类实例
- java - 将序列图转换为 Java 代码
- python - 使用不同颜色绘制多个函数,包括导数
- powershell - 在 powershell 脚本中添加空行会产生错误
- java - HTTP 响应没有给出输出
- python - 将行中的数据转置为列
- squish - 如何在 squish 中加速工作空间的构建?
- android - 将个人位置添加到 Google Place 自动完成列表