接触PHP快3年了都是做业务逻辑树结构用得真是不多。就生成个菜单树居然还用到递归时间复杂度阶数级上升这还是以前培训的时候老师演示的“无限级分类”有更厉害的同学直接在循环里面查询数据库了数量少的时候真没什么区别。这几年一直这么用直到稍微了解一点数据结构的概念才不得不把这个过程重新写一遍要不然不舒服。换个思路没想到可以这么简洁复杂度 O(n)
/*** 获取菜单树数组* * return array*/public static function getMenuTree(){$obj self::select(id,pid,text,icon,url)->where(status,1)->get()->toArray();$rows [];// 把主键作为索引foreach ($obj as $row) {$rows[$row[id]] $row;}$menus [];foreach ($rows as pid]]??null;// 一次循环找到各自的父级就可以if($parent){ $parent[sub][] // 注意要按引用传递}elseif(-1$row[pid]){$menus[] }unset($row[id],$row[pid]);}return $menus;}
[{"text":"数据","icon":"chart","url":"","sub":[{"text":"充值记录","icon":"","url":"rechargeRecord"},{"text":"管理員列表","icon":"","url":"user"},{"text":"官網設置","icon":"","url":"homeSetting"},{"text":"礼包日志","icon":"","url":"giftLog"}]}]
转:https://www.cnblogs.com/liaozt/p/6048931.html