php无限级分类并且把子分类包含进父类中
$data = [
['id'=>'1','data_name'=>'四川','pid'=>'0'],
['id'=>'2','data_name'=>'江苏','pid'=>'0'],
['id'=>'3','data_name'=>'重庆','pid'=>'0'],
['id'=>'4','data_name'=>'成都','pid'=>'1'],
['id'=>'5','data_name'=>'双流','pid'=>'4'],
['id'=>'6','data_name'=>'南京','pid'=>'2'],
['id'=>'7','data_name'=>'淮安','pid'=>'6'],
['id'=>'8','data_name'=>'渝北区','pid'=>'3'],
['id'=>'9','data_name'=>'观音桥','pid'=>'8'],
['id'=>'10','data_name'=>'小郡肝串串','pid'=>'5'],
];
function catTree($data,$id=0,$lev=0)
{
$city = [];
//遍历数组
foreach ($data as $k => $v)
{
//如果$data['pid'] == id就装到$city中并把$data['id']当传参传入函数中
if($v['pid'] == $id)
{
$v['leval'] = $lev;
$child = catTree($data,$v['id'],$lev+1);//如果有值就是子类
if(!empty($child))
{
$v['children'] = $child;
}
$city[] = $v;
}
}
return $city;
}
$res = catTree($data);
echo '<pre>';
print_r($res);