PHP 无限级分类(递归)

时间:2022-04-10 08:39:54
网上有很多,这是我自己做测试用的


$arr = array(
array('id'=>1,'name'=>'电脑','pid'=>0),
array('id'=>2,'name'=>'手机','pid'=>0),
array('id'=>3,'name'=>'笔记本','pid'=>1),
array('id'=>4,'name'=>'台式机','pid'=>1),
array('id'=>5,'name'=>'智能机','pid'=>2),
array('id'=>6,'name'=>'功能机','pid'=>2),
array('id'=>7,'name'=>'超级本','pid'=>3),
array('id'=>8,'name'=>'游戏本','pid'=>3),
);

/**
* @param $arr 数组
* @param $id id
* @param $level 层级
* @return array
*/
function demo($arr,$id,$level)
{
$list =array();
foreach ($arr as $k=>$v){
if ($v['pid'] == $id){
$v['level']=$level;
$v['son'] = demo($arr,$v['id'],$level+1);
$list[] = $v;
}
}
return $list;
}
echo "<pre>";
print_r(demo($arr,0,0));


输出结果:
Array
(
[0] => Array
(
[id] => 1
[name] => 电脑
[pid] => 0
[level] => 0
[son] => Array
(
[0] => Array
(
[id] => 3
[name] => 笔记本
[pid] => 1
[level] => 1
[son] => Array
(
[0] => Array
(
[id] => 7
[name] => 超级本
[pid] => 3
[level] => 2
[son] => Array
(
)

)

[1] => Array
(
[id] => 8
[name] => 游戏本
[pid] => 3
[level] => 2
[son] => Array
(
)

)

)

)

[1] => Array
(
[id] => 4
[name] => 台式机
[pid] => 1
[level] => 1
[son] => Array
(
)

)

)

)

[1] => Array
(
[id] => 2
[name] => 手机
[pid] => 0
[level] => 0
[son] => Array
(
[0] => Array
(
[id] => 5
[name] => 智能机
[pid] => 2
[level] => 1
[son] => Array
(
)

)

[1] => Array
(
[id] => 6
[name] => 功能机
[pid] => 2
[level] => 1
[son] => Array
(
)

)

)

)

)