标签:int color .com print function 类的方法 tree 代号 递归
<?php $data[]=array(‘id‘=>1,‘parentid‘=>0,‘name‘=>‘中国‘); $data[]=array(‘id‘=>2,‘parentid‘=>0,‘name‘=>‘美国‘); $data[]=array(‘id‘=>3,‘parentid‘=>0,‘name‘=>‘韩国‘); $data[]=array(‘id‘=>4,‘parentid‘=>1,‘name‘=>‘北京‘); $data[]=array(‘id‘=>5,‘parentid‘=>1,‘name‘=>‘上海‘); $data[]=array(‘id‘=>6,‘parentid‘=>1,‘name‘=>‘广西‘); $data[]=array(‘id‘=>7,‘parentid‘=>6,‘name‘=>‘桂林‘); $data[]=array(‘id‘=>8,‘parentid‘=>6,‘name‘=>‘南宁‘); $data[]=array(‘id‘=>9,‘parentid‘=>6,‘name‘=>‘柳州‘); $data[]=array(‘id‘=>10,‘parentid‘=>2,‘name‘=>‘纽约‘); $data[]=array(‘id‘=>11,‘parentid‘=>2,‘name‘=>‘华盛顿‘); $data[]=array(‘id‘=>12,‘parentid‘=>3,‘name‘=>‘首尔‘); $tree=build_tree($data,0); print_r($tree); function findChild($arr,$id){ $childs=array(); //定义一个数组 foreach ($arr as $k => $v){ //把父级二维数组遍历 if($v[‘parentid‘]== $id){ //判断子集的parentid的值是不是等于父级id的值 $childs[]=$v; //如果等于把这个子集交给变量数组$childs } } return $childs; //返回符合条件的所有子集 } function build_tree($rows,$root_id){ //$root_id父级代号 $childs=findChild($rows,$root_id); if(empty($childs)){ return null; } foreach ($childs as $k => $v){ //遍历符合父级id值的数组 $rescurTree=build_tree($rows,$v[‘id‘]); //把子集再遍历,如果有子集就交给$rescurTree if( null != $rescurTree){ $childs[$k][‘childs‘]=$rescurTree; //把子集的子集交给$childs[$k][‘childs‘],[‘childs‘]是自定义的一个键值
} } return $childs; } ?>
标签:int color .com print function 类的方法 tree 代号 递归
原文地址:http://www.cnblogs.com/xingyue1988/p/6233122.html