转载来源:
//模拟一个分类数组$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) { $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);//string str_repeat ( string $input , int $multiplier )//返回 input 重复 multiplier 次后的结果。foreach($tree as $v) { echo str_repeat(' |- ',$v['lev']),$v['name'],''; //str_repeat — 重复一个字符串}/** *结果 *//*|- 安徽|- |- 淮北|- |- |- 濉溪县|- 北京|- |- 海淀|- |- |- 上地|- |- 昌平|- |- 朝阳*//** *递归,求家谱树 */function familytree($arr,$id) { $tree = array(); foreach($arr as $v) { if($v['id'] == $id) { // 判断要不要找父栏目 if($v['parent'] > 0) { // parnet>0,说明有父栏目 $tree = array_merge($tree,familytree($arr,$v['parent'])); } $tree[] = $v; // 以找到上地为例 } } return $tree;}print_r(familytree($area,8)); // 北京->海淀->上地echo "";/** *迭代,求家谱树 */// 迭代,效率比递归高,代码也没多.// 找家谱树推荐用迭代function tree($arr,$id) { $tree = array(); while($id !== 0) { foreach($arr as $v) { if($v['id'] == $id) { $tree[] = $v; $id = $v['parent']; break; } } } return $tree;}print_r(tree($area,8));