<?php
$arr = [
[
'id' => 1,
'name' => '衣服',
'p_id' => 0
],
[
'id' => 2,
'name' => '鞋子',
'p_id' => 0
],
[
'id' => 3,
'name' => '帽子',
'p_id' => 0
],
[
'id' => 4,
'name' => '女毛衣',
'p_id' => 1
],
[
'id' => 5,
'name' => '男毛衣',
'p_id' => 1
],
[
'id' => 6,
'name' => '女衬衫',
'p_id' => 1
],
[
'id' => 7,
'name' => '男衬衫',
'p_id' => 1
],
[
'id' => 8,
'name' => '男鞋',
'p_id' => 2
],
[
'id' => 9,
'name' => '女鞋',
'p_id' => 2
],
[
'id' => 10,
'name' => '带沿帽',
'p_id' => 3
],
[
'id' => 11,
'name' => '不带沿帽',
'p_id' => 3
],
[
'id' => 12,
'name' => '高帽',
'p_id' => 3
],
];
function digui($arr, $p_id = 0, $level = 0){
//声明静态数组,避免递归调用时,多次声明导致数组覆盖
static $list = [];
foreach ($arr as $key => $value){
//第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
if ($value['p_id'] == $p_id){
//父节点为根节点的节点,级别为0,也就是第一级
$value['level'] = $level;
//把数组放到list中
$list[] = $value;
//把这个节点从数组中移除,减少后续递归消耗
unset($arr[$key]);
//开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
digui($arr, $value['id'], $level+1);
}
}
return $list;
// $data = NULL;
// foreach($arr as $k => $v){
// if($v['p_id'] == $p_id){
// $v['level'] = $level;
// $v['son'] = digui($arr, $level = $level+1, $v['id']);
// $data[] = $v;
// }
// }
// return $data;
}
$data = digui($arr);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>递归</title>
</head>
<body>
<table>
<?php foreach($data as $k => $v){?>
<tr>
<td><?php echo str_repeat(' ', $v['level']).$v['name'];?></td>
</tr>
<?php }?>
</table>
</body>
</html>
PHP实现递归并展示
最新推荐文章于 2021-09-15 16:08:44 发布