本文實例講述了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數組(Array)操作技巧大全》、《php排序算法總結》、《PHP常用遍歷算法與技巧總結》、《PHP數據結構與算法教程》、《php程序設計算法總結》、《PHP數學運算技巧總結》、《php正則表達式用法總結》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。