<?php
$array = array(
array('id' => 1, 'pid' => 0, 'n' => '河北省'),
array('id' => 2, 'pid' => 0, 'n' => '北京市'),
array('id' => 3, 'pid' => 1, 'n' => '邯郸市'),
array('id' => 4, 'pid' => 2, 'n' => '朝阳区'),
array('id' => 5, 'pid' => 2, 'n' => '通州区'),
array('id' => 6, 'pid' => 4, 'n' => '望京'),
array('id' => 7, 'pid' => 4, 'n' => '酒仙桥'),
array('id' => 8, 'pid' => 3, 'n' => '永年区'),
array('id' => 9, 'pid' => 1, 'n' => '武安市'),
array('id' => 10, 'pid' => 8, 'n' => '永年区镇'),
array('id' => 11, 'pid' => 0, 'n' => '上海市'),
array('id' => 12, 'pid' => 0, 'n' => '湖北省'),
array('id' => 13, 'pid' => 12, 'n' => '武汉市'),
array('id' => 14, 'pid' => 12, 'n' => '随州市'),
array('id' => 15, 'pid' => 14, 'n' => '曾都区'),
);
function getTree($array, $pid=0){
$tree = array();
foreach ($array as $key => $value) {
if ($value['pid'] == $pid) {
$value['children'] = getTree($array, $value['id']);
$tree[] = $value;
}
}
return $tree;
}
$list=getTree($array);
echo json_encode($list);
php递归树型数组
最新推荐文章于 2024-02-29 11:33:10 发布