2,
'pid' => 1,
'title' => '济南',
],
[
'id' => 3,
'pid' => 1,
'title' => '滨州',
],
[
'id' => 4,
'pid' => 2,
'title' => '历城区',
],
[
'id' => 5,
'pid' => 2,
'title' => '历下区',
],
[
'id' => 6,
'pid' => 3,
'title' => '沾化',
],
[
'id' => 7,
'pid' => 3,
'title' => '无棣',
],
[
'id' => 1,
'pid' => 0,
'title' => '山东',
],
[
'id' => 8,
'pid' => 0,
'title' => '北京',
],
[
'id' => 9,
'pid' => 8,
'title' => '朝阳区',
],
];
$res = [];
function get_attr($arr,$pid){
$tree = array(); //每次都声明一个新数组用来放子元素
foreach($arr as $v){
if($v['pid'] == $pid){ //匹配子记录
$v['child'] = get_attr($arr,$v['id']); //递归获取子记录
if($v['child'] == null){
unset($v['child']); //如果子元素为空则unset()进行删除,说明已经到该分支的最后一个元素了(可选)
}
$tree[] = $v; //将记录存入新数组
}
}
return $tree; //返回新数组
}
$res = get_attr($arr, 0);
var_dump($res);