实现无限级分类之前,准备数组(此处可以换成你自己需要实现无限级分类的资源) <?php $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'), ); echo "<pre>"; var_dump($array);
(1) .递归实现
function getTree($array, $pid =0, $level = 0){
//声明静态数组,避免递归调用时,多次声明导致数组覆盖
static $list = [];
foreach ($array as $key => $value){
//第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
if ($value['pid'] == $pid){
//父节点为根节点的节点,级别为0,也就是第一级
$value['level'] = $level;
//把数组放到list中
$list[] = $value;
//把这个节点从数组中移除,减少后续递归消耗
unset($array[$key]);
//开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
getTree($array, $value['id'], $level+1);
}
}
return $list;
}
结果如图:
(2) .树结构
function getTree($items,$pid ="pid") {
$map = [];
$tree = [];
foreach ($items as &$it){
$map[$it['id']] = &$it;
} //数据的ID名生成新的引用索引树
foreach ($items as &$at){
$parent = &$map[$at[$pid]];
if($parent) {
$parent['children'][] = &$at;
}else{
$tree[] = &$at;
}
}
return $tree;
}
或者(拿到借助框架或者函数处理好的格式化好的树的时候,可以直接传入下面的函数处理)
function getTree($items) {
$tree = array(); //格式化好的树
foreach ($items as $item)
if (isset($items[$item['pid']]))
$items[$item['pid']]['son'][] = &$items[$item['id']];
else
$tree[] = &$items[$item['id']];
return $tree;
}
结果如图: