版权声明:阿西莫多 https://blog.csdn.net/yang_yun_hao/article/details/83578767
public function recursion($list, $newArr=[], $pid = '0',$level = 0){
$newArr = []; // 新数组用于存放数据
if (!empty($list)) {
foreach ($list as $k => &$v) {
if ($v['pid'] == $pid) { // 如果父ID与pid相同则为父级数组
$v['level'] = $level; // 层级
$v['child'] = $this->recursion($list, $newArr, $v['id'],$level+1); // 递归处理数据
$newArr[] = $v; // 新数据放入数组准备返回
}
}
}
return $newArr;
// 使用方法
/*$city = DB::table('citylist')->get();
$arr = json_decode(json_encode($city),true);
print_r($this->recursion($arr));*/
}