分类、地区递归展示数据

$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' => '上海市')
);

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;
}

$data = getTree($array);
var_dump($data);

测试后结果顺利

你可能感兴趣的:(PHP,php)