- 数据
- 递归实现
- 引用实现
递归实现:
$arr = [
0=>[
'id' =>1
'pid' =>0,
'name'=>'人员管理'
],
1=>[
'id' =>2
'pid' =>1,
'name'=>'人员添加'
],
2=>[
'id' =>3
'pid' =>2,
'name'=>'人员XX'
]
];
function getTree($pid,$arr){
$treeArr = [];
foreach($arr as $k=>$v){
if($v['pid']==$pid){
$v['child'] = getTree($v['id'],$arr);
}
$treeArr[] = $v;
}
}
getTree(0,$arr);
引用实现:
function getTree($arr){
$itemArr = [];
foreach($arr as $k=>$v){
$itemArr[$v['id']] = $v;
}
$treeArr = [];
foreach($itemArr as $k=>$v){
if(isset($itemArr[$v['pid']])){
$itemArr[$v['pid']]['child'] = &$v;
}else{
$treeArr[] = &$v;
}
}
}