php部分,一個用遞迴無限分類的方法

來源:互聯網
上載者:User

標籤: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; } ?>

 

 

php部分,一個用遞迴無限分類的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.