递归
$array = array(
array('id' => 1, 'pid' => 0, 'name' => '河北省'),
array('id' => 2, 'pid' => 0, 'name' => '北京市'),
array('id' => 3, 'pid' => 1, 'name' => '邯郸市'),
array('id' => 4, 'pid' => 2, 'name' => '朝阳区'),
array('id' => 5, 'pid' => 2, 'name' => '通州区'),
array('id' => 6, 'pid' => 4, 'name' => '望京'),
array('id' => 7, 'pid' => 4, 'name' => '酒仙桥'),
array('id' => 8, 'pid' => 3, 'name' => '永年区'),
array('id' => 9, 'pid' => 1, 'name' => '武安市'),
);
/**
* 递归实现无限极分类
* @param $array 分类数据
* @param $pid 父ID
* @param $level 分类级别
* @return $list 分好类的数组 直接遍历即可 $level可以用来遍历缩进
*/
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;
}
/*
* 获得递归完的数据,遍历生成分类
*/
$array = getTree($array);
foreach($array as $value){
echo str_repeat('--', $value['level']), $value['name'].'<br />';
}
引用
$array = array(
array('auth_id' => 100, 'auth_name' => '后台首页', 'auth_pid' => 0),
array('auth_id' => 116, 'auth_name' => '管理员', 'auth_pid' => 0),
array('auth_id' => 120, 'auth_name' => '管理员列表', 'auth_pid' => 116),
array('auth_id' => 121, 'auth_name' => '管理员添加', 'auth_pid' => 116),
array('auth_id' => 122, 'auth_name' => '数据一览', 'auth_pid' => 100),
array('auth_id' => 123, 'auth_name' => '更新日志', 'auth_pid' => 100),
array('auth_id' => 124, 'auth_name' => '猜猜看', 'auth_pid' => 123),
);
function generateTree($data){
//构建一个新数组,key为自己的id,为第二步做铺垫
$items = array();
foreach($data as $v){
$items[$v['auth_id']] = $v;
}
$tree = array();
foreach($items as $k => $item){
//判断是否是顶级分类
if(isset($items[$item['auth_pid']])){
$items[$item['auth_pid']]['son'][] = &$items[$k]; //引用赋值
}else{
$tree[] = &$items[$k];
}
}
return $tree;
}
$data = generateTree($array);
网友评论