<?php
header('Content-type:text/html;charset=utf8');


$address = array(
    array('id'=>1  , 'address'=>'安徽' , 'pid' => 0),
    array('id'=>2  , 'address'=>'江苏' , 'pid' => 0),
    array('id'=>3  , 'address'=>'合肥' , 'pid' => 1),
    array('id'=>4  , 'address'=>'庐阳区' , 'pid' => 3),
    array('id'=>5  , 'address'=>'大杨镇' , 'pid' => 4),
    array('id'=>6  , 'address'=>'南京' , 'pid' => 2),
    array('id'=>7  , 'address'=>'玄武区' , 'pid' => 6),
    array('id'=>8  , 'address'=>'梅园新村街道', 'pid' => 7),
    array('id'=>9  , 'address'=>'上海' , 'pid' => 0),
    array('id'=>10 , 'address'=>'黄浦区' , 'pid' => 9),
    array('id'=>11 , 'address'=>'外滩' , 'pid' => 10),
    array('id'=>12 , 'address'=>'安庆' , 'pid' => 1)
);



//$tree = [];
function vTree($data, $pid = 0, $step = 0, &$tree = []){
        foreach ($data as $key => $val) {
            if ($val['pid'] == $pid) {
                $val['address'] = str_repeat('', $step) . "&nbsp;" . $val['address'];
                $tree[] = $val;
                vTree($data, $val['id'], $step + 1, $tree);
            }
        }

        return $tree;
    }

$data = vTree($address);

foreach ($data as $key => $val) {
    echo $val['address'] . '<br />';
}


function dump($data){
    echo "<pre>";
    print_r($data);
    echo "</pre>";
}


?>


安徽
- 合肥
-- 庐阳区
--- 大杨镇
- 安庆
 江苏
- 南京
-- 玄武区
--- 梅园新村街道
 上海
- 黄浦区
-- 外滩

 

相信坚持的力量,日复一日的习惯.