php 用遞迴實現的無限層級分類

來源:互聯網
上載者:User

標籤:遞迴   無線層級分類   

<?php
header("Content-type:text/html; charset=utf-8");
/**
 * 
 * @category contry_category 實現一個無限層級分類,類似種類的劃分,常用在欄目導航
 * 
 */


/**
 +-------------------------------------------------------------------------------+
 |             id       name         類別id                                      |
 |              1       中國           0                                         |
 |              2       北京           1                                         |
 |              3       上海           1                                         |
 |              4       美國           0                                         |
 *              5       紐約           4                                         *
 *              6      華盛頓          4                                         *
 *              7    加州福尼亞        4                                         *
 +-------------------------------------------------------------------------------+
 * 
 *    類別id 為0的是頂級欄目
 *    類別id 為id相同的是所屬分類
 */


class contry_category{
     public $i =-1;
     public function index($array){
         $this->i++;
         if($array[$this->i][‘category_id‘]==0){
             echo "├".$array[$this->i]["name"]."<br />";
             for($j=0;$j<  count($array);$j++){
                if($array[$j][‘category_id‘]==$array[$this->i][‘id‘]){     //查看所屬分類
                     echo "├─┴".$array[$j]["name"]."<br />";
                }
             }
         }
         foreach($array as $v){
             if($v[‘category_id‘]==0)
             $ary[]=$v[‘category_id‘];        //擷取幾個頂級欄目,來確定遞迴幾次
         }
         
         if($this->i<=count($ary))            
              $this->index($array);            //遞迴
     }
}
$infos = array(array("id"=>1,‘name‘=>"中國","category_id"=>0),array("id"=>2,‘name‘=>"北京","category_id"=>1),array("id"=>3,‘name‘=>"上海","category_id"=>1),array("id"=>4,‘name‘=>"美國","category_id"=>0),array("id"=>5,‘name‘=>"紐約","category_id"=>4),array("id"=>6,‘name‘=>"華盛頓","category_id"=>4),array("id"=>7,‘name‘=>"加州福尼亞","category_id"=>4));
 
$obj =new contry_category();
$obj->index($infos);






/**
 * 列印出來的效果是這樣
 *  ├中國
    ├─┴北京
    ├─┴上海
    ├美國
    ├─┴紐約
    ├─┴華盛頓
    ├─┴加州福尼亞
 */

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.