php不使用递归的无限级分类

时间:2022-10-24 16:23:09


function classify($arr){
$list=array();
foreach ($arr as $key => $value) {
if (isset($arr[$value['pid']])) {
$arr[$value['pid']]['son'][]=&$arr[$value['id']];
}else{
$list[]=&$arr[$value['id']];
}
}
return $list;
}
$arr = array(
    1 => array('id' => 1, 'pid' => 0, 'name' => '安徽省'),
    2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'),
    3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'),
    4 => array('id' => 4, 'pid' => 3, 'name' => '长丰县'),
    5 => array('id' => 5, 'pid' => 1, 'name' => '安庆市'),
    6 =>array('id' => 6, 'pid' => 5, 'name' => '百花县'),
);
echo '<pre>';
print_r(classify($arr));