PHP之递归函数 发表于 2019-09-26 分类于 数据与结构 1234567891011121314151617181920212223$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));// 思路:先递后归,先把最后一层的数据找到,然后再回归。