根据引用实现索引树(无限极分类)

$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 ))))


【根据引用实现索引树(无限极分类)】转载于:https://my.oschina.net/u/3482593/blog/3076232

    推荐阅读