PHP之递归函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$list = [
['id' => 1, 'p_id' => 0, 'city' => '湖南'],
['id' => 2, 'p_id' => 1, 'city' => '郴州'],
['id' => 3, 'p_id' => 2, 'city' => '嘉禾'],
['id' => 4, 'p_id' => 1, 'city' => '永州'],
];

function recursive($list, $pid = 0)
{
$retList = [];
foreach ($list as $key => $item) {
if ($pid == $item['p_id']) {
//返回的是下一层的$retList数组,如果没有符合值则返回空
$item['child'] = recursive($list, $item['id']);
//把同一层的放在一个数组里,如这里的p_id = 0
$retList[] = $item;
}
}
return $retList;
}
print_r(recursive($list));

// 思路:先递后归,先把最后一层的数据找到,然后再回归。