```
$area = array(
array('id'=>1,'area'=>'北京','pid'=>0),
array('id'=>2,'area'=>'上海','pid'=>0),
array('id'=>3,'area'=>'四川','pid'=>0),
array('id'=>4,'area'=>'成都','pid'=>3),
array('id'=>5,'area'=>'海淀','pid'=>1),
array('id'=>6,'area'=>'龙泉','pid'=>4),
array('id'=>7,'area'=>'中关村','pid'=>5),
array('id'=>8,'area'=>'徐家汇','pid'=>2),
array('id'=>9,'area'=>'徐家汇商城','pid'=>8),
array('id'=>10,'area'=>'闵行区','pid'=>2),
array('id'=>11,'area'=>'华东师范','pid'=>10),
array('id'=>12,'area'=>'广东','pid'=>0),
array('id'=>13,'area'=>'深圳','pid'=>12),
array('id'=>14,'area'=>'宝安','pid'=>13),
array('id'=>15,'area'=>'沙井','pid'=>14),
array('id'=>16,'area'=>'上南','pid'=>15),
array('id'=>17,'area'=>'南浦','pid'=>16),
array('id'=>18,'area'=>'松岗','pid'=>14),
array('id'=>19,'area'=>'江边','pid'=>18),
array('id'=>20,'area'=>'光明','pid'=>13),
array('id'=>21,'area'=>'松福','pid'=>19),
);
//*******递归查找子子孙孙树
function subtree($arr,$pid=0,$lev=1){
// static $subs = array();
$subs = array();
foreach($arr as $v){
if($v['pid'] == $pid){
$v['lev']= $lev;
$subs[] = $v;
$subs = array_merge($subs,subtree($arr,$v['id'],$lev+1));
}
}
return $subs;
}
// var_dump($area);
//*******递归查找子子孙孙树2
function getTree($ar,$pid,$lev=0){
static $tree=array();
foreach ($ar as $k=>$v) {
if ($v['pid']==$pid) {
$v['lev']=$lev;
$tree[]=$v;
unset($ar[$k]);
getTree($ar,$v['id'],$lev+1);
}
}
return $tree;
}
//*******不用递归,用迭代法查找子子孙孙树
function DTree($arr,$pid=0){
$task = array($pid);//任务表
$tree = array();//地区表
while(!empty($task)){
$flag = false;
foreach ($arr as $k => $v) {
if($v['pid'] == $pid){
$tree[] = $v;
array_push($task,$v['id']);//把最新的地区id入任务栈
$pid = $v['id'];
unset($arr[$k]);//把找到的单元unset掉
$flag = true;//说明找到了子栏目
}
}
if($flag == false){
array_pop($task);
$pid = end($task);
}
}
return $tree;
}
echo '#################';
echo '
';
print_r(DTree($area,0));
echo '';
echo '#################';
$tree = subtree($area,0,$lev=1);
echo '
';
// print_r($area);
// print_r($tree);
echo '';
foreach ($tree as $v) {
echo str_repeat(' ', $v['lev']).$v['area'].'
';
}
echo '
';
$aaa=array(
'a','b');
$bbb=array(
0=>'aa',1=>'bb','cc','dd');
print_r($aaa += $bbb);
// print_r(array_merge($aaa,$bbb));
//******在数组中查找面包屑导航,根据ID查找他的所有祖先
function navtree($arr,$id){
static $tree = array();
foreach($arr as $v){
if($v['id'] == $id){
if($v['pid'] > 0){
navtree($arr,$v['pid']);
}
array_push($tree,$v) ;
}
}
return $tree;
}
//******在数组中查找面包屑导航,根据ID查找他的所有祖先
function navtree2($arr,$id){
$tree = array();
foreach($arr as $v){
if($v['id'] == $id){
if($v['pid'] > 0){
$tree = array_merge($tree,navtree($arr,$v['pid']));
}
$tree[]=$v;
}
}
return $tree;
}
//******,不用递归使用迭代的方法
function ntree($arr,$id){
$tree = array();
while($id !== 0){
foreach($arr as $v){
if($v['id']==$id){
$tree[]=$v;
$id = $v['pid'];
break;
}}}
return array_reverse($tree);
}
echo '
';
$res = ntree($area,17) ;
echo '
';
echo '
';
print_r($res) ;
echo '';
for($i=0;$i
echo ''.$res[$i]['area'].'';
if($i+1
echo '>>>';
}
}
```