$array = array(
0=>array('id'=>1,'uid'=>0,'menuname'=>'菜单1','url'=>0,'addtime'=>'2018-08-29 16:36:55'),
1=>array('id'=>2,'uid'=>0,'menuname'=>'菜单2','url'=>0,'addtime'=>'2018-08-29 16:36:55'),
2=>array('id'=>3,'uid'=>1,'menuname'=>'1子菜单1','url'=>0,'addtime'=>'2018-08-29 16:36:55'),
3=>array('id'=>4,'uid'=>3,'menuname'=>'1子菜单2','url'=>0,'addtime'=>'2018-08-29 16:36:55'),
4=>array('id'=>5,'uid'=>2,'menuname'=>'2子菜单1','url'=>0,'addtime'=>'2018-08-29 16:36:55'),
);
function getTree($items,$pid ="uid") {
$map = [];
$tree = [];
foreach ($items as &$it) $map[$it['id']] = &$it; //数据的ID名生成新的引用索引树
foreach ($items as $k => &$at){
$parent = &$map[$at[$pid]];
if($parent) {
$parent['children'][] = &$at;
}else{
$tree[] = &$at;
}
}
return $tree;
}
print_r(getTree($array));die;
出来的效果是
Array
(
[0] => Array
(
[id] => 1
[uid] => 0
[menuname] => 菜单1
[url] => 0
[addtime] => 2018-08-29 16:36:55
[children] => Array
(
[0] => Array
(
[id] => 3
[uid] => 1
[menuname] => 1子菜单1
[url] => 0
[addtime] => 2018-08-29 16:36:55
[children] => Array
(
[0] => Array
(
[id] => 4
[uid] => 3
[menuname] => 1子菜单2
[url] => 0
[addtime] => 2018-08-29 16:36:55
)
)
)
)
)
[1] => Array
(
[id] => 2
[uid] => 0
[menuname] => 菜单2
[url] => 0
[addtime] => 2018-08-29 16:36:55
[children] => Array
(
[0] => Array
(
[id] => 5
[uid] => 2
[menuname] => 2子菜单1
[url] => 0
[addtime] => 2018-08-29 16:36:55
)
)
)
)