本文主要是介绍递归 迭代 得到家谱树 子孙树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<?php $arr=array(array('id'=>'1','name'=>'吉林','parent'=>0),array('id'=>'2','name'=>'北京','parent'=>0),array('id'=>'3','name'=>'辽宁','parent'=>0),array('id'=>'4','name'=>'吉林市','parent'=>1),array('id'=>'5','name'=>'长春','parent'=>1),array('id'=>'6','name'=>'海淀','parent'=>2),array('id'=>'7','name'=>'大连','parent'=>3),array('id'=>'8','name'=>'船营区','parent'=>4),array('id'=>'9','name'=>'丰满区','parent'=>4));//找子栏目function findson($arr,$id=0){$sons=array();foreach($arr as $v){if($v['parent']==$id){$sons[]=$v;}}return $sons;}//var_dump(findson($arr,$id=1));//找子孙树//用静态变量function subtree($arr,$id,$lev=1){static $subs=array(); //static 只初始化一次foreach($arr as $v){if($v['parent']==$id){$v['lev']=$lev;$subs[]=$v;subtree($arr,$v['id'],$lev+1);//不用静态变量// $subs=array_merge($subs,subtree($arr,$v['id'],$lev+1));}}return $subs;}/*$tree=subtree($arr,$id=0,1);foreach ($tree as $v){echo str_repeat(' ',$v['lev']).$v['name']."<br/>";}*//**家谱树应用面包屑导航首页>手机类型>诺基亚>**/function familytree($area,$id){static $tree=array();foreach($area as $v){if($v['id']==$id){$tree[]=$v;//判断要不要继续找父栏目if($v['parent']>0){familytree($area,$v['parent']);//不用static//array_merge($area,familytree($area,$v['parent']));}}}return $tree;}echo "<hr>";
//print_r(familytree($arr,9));
/*用迭代找家谱树(推荐)*/
function familytree2($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(familytree2($arr,9));
?>
这篇关于递归 迭代 得到家谱树 子孙树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!