接触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 &$row) {
$parent = &$rows[$row['pid']]??null;
// 一次循环找到各自的父级就可以
if($parent){
$parent['sub'][] = &$row; // 注意要按引用传递
}elseif(-1===$row['pid']){
$menus[] = &$row;
}
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"}
]
}
]