$area = array( array(‘id‘=>1,‘name‘=>‘安徽‘,‘parent‘=>0), array(‘id‘=>2,‘name‘=>‘海淀‘,‘parent‘=>7), array(‘id‘=>3,‘name‘=>‘濉溪县‘,‘parent‘=>5), array(‘id‘=>4,‘name‘=>‘昌平‘,‘parent‘=>7), array(‘id‘=>5,‘name‘=>‘淮北‘,‘parent‘=>1), array(‘id‘=>6,‘name‘=>‘朝阳‘,‘parent‘=>7), array(‘id‘=>7,‘name‘=>‘北京‘,‘parent‘=>0), array(‘id‘=>8,‘name‘=>‘上地‘,‘parent‘=>2) ); // 找子孙树 // 用静态变量 /* function subtree($arr,$id=0,$lev=1) { static $subs = array(); // 子孙数组 foreach($arr as $v) { if($v[‘parent‘] == $id) { $v[‘lev‘] = $lev; $subs[] = $v; // 举例说找到array(‘id‘=>1,‘name‘=>‘安徽‘,‘parent‘=>0), subtree($arr,$v[‘id‘],$lev+1); } } return $subs; } // print_r(subtree($area,0,1)); */ function subtree($arr,$id=0,$lev=1) { $subs = array(); // 子孙数组 foreach($arr as $v) { if($v[‘parent‘] == $id) { $v[‘lev‘] = $lev; $subs[] = $v; // 举例说找到array(‘id‘=>1,‘name‘=>‘安徽‘,‘parent‘=>0), $subs = array_merge($subs,subtree($arr,$v[‘id‘],$lev+1)); } } return $subs; } $tree = subtree($area,0,1); foreach($tree as $v) { echo str_repeat(‘ ‘,$v[‘lev‘]),$v[‘name‘],‘<br />‘; }
原文:http://www.cnblogs.com/zzg521/p/4276231.html