瞧,那夕阳边的云霞,好似得到了夕阳的赏赐,变得欣喜异常,时而围坐一团,倾诉衷肠;时而围着夕阳跳起了探戈;更有自我陶醉的,远离他人,自我欣赏……
本文实例讲述了PHP递归遍历多维数组实现无限分类的方法。分享给大家供大家参考,具体如下:
<?php //$data[]=array('id'=>1,'parentid'=>0,'name'=>'中国','img'=>'52091199'); $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); //echo memory_get_usage(); print_r($tree); function findChild(&$arr,$id){ $childs=array(); foreach ($arr as $k => $v){ if($v['parentid']== $id){ $childs[]=$v; } } return $childs; } function build_tree($rows,$root_id){ $childs=findChild($rows,$root_id); if(empty($childs)){ return null; } foreach ($childs as $k => $v){ $rescurTree=build_tree($rows,$v['id']); if( null != $rescurTree){ $childs[$k]['childs']=$rescurTree; } } return $childs; } ?>
运行结果:
Array ( [0] => Array ( [id] => 1 [parentid] => 0 [name] => 中国 [childs] => Array ( [0] => Array ( [id] => 4 [parentid] => 1 [name] => 北京 ) [1] => Array ( [id] => 5 [parentid] => 1 [name] => 上海 ) [2] => Array ( [id] => 6 [parentid] => 1 [name] => 广西 [childs] => Array ( [0] => Array ( [id] => 7 [parentid] => 6 [name] => 桂林 ) [1] => Array ( [id] => 8 [parentid] => 6 [name] => 南宁 ) [2] => Array ( [id] => 9 [parentid] => 6 [name] => 柳州 ) ) ) ) ) [1] => Array ( [id] => 2 [parentid] => 0 [name] => 美国 [childs] => Array ( [0] => Array ( [id] => 10 [parentid] => 2 [name] => 纽约 ) [1] => Array ( [id] => 11 [parentid] => 2 [name] => 华盛顿 ) ) ) [2] => Array ( [id] => 3 [parentid] => 0 [name] => 韩国 [childs] => Array ( [0] => Array ( [id] => 12 [parentid] => 3 [name] => 首尔 ) ) ) )
希望本文所述对大家PHP程序设计有所帮助。
本文PHP递归遍历多维数组实现无限分类的方法到此结束。人生是美好的,又是短暂的。有的人生寂寞,有的人生多彩,不同的人有着不同的人生追求;人生是一条没有回程的单行线,每个人都用自己的所有时光前行。小编再次感谢大家对我们的支持!