PHP無限級分類實現(遞迴+非遞迴)

來源:互聯網
上載者:User

標籤:ext   pre   ret   tree   function   text   print   key   智能機   

<?php  /**  * Created by PhpStorm.  * User: qishou  * Date: 15-8-2  * Time: 上午12:00  */  //準備數組,代替從資料庫中檢索出的資料(共有三個必須欄位id,name,pid)  header("content-type:text/html;charset=utf-8");  $categories = array(      array(‘id‘=>1,‘name‘=>‘電腦‘,‘pid‘=>0),      array(‘id‘=>2,‘name‘=>‘手機‘,‘pid‘=>0),      array(‘id‘=>3,‘name‘=>‘筆記本‘,‘pid‘=>1),      array(‘id‘=>4,‘name‘=>‘台式機‘,‘pid‘=>1),      array(‘id‘=>5,‘name‘=>‘智能機‘,‘pid‘=>2),      array(‘id‘=>6,‘name‘=>‘功能機‘,‘pid‘=>2),      array(‘id‘=>7,‘name‘=>‘超級本‘,‘pid‘=>3),      array(‘id‘=>8,‘name‘=>‘遊戲本‘,‘pid‘=>3),  );    /*======================非遞迴實現========================*/  $tree = array();  //第一步,將分類id作為數組key,並建立children單元  foreach($categories as $category){      $tree[$category[‘id‘]] = $category;      $tree[$category[‘id‘]][‘children‘] = array();  }  //第二步,利用引用,將每個分類添加到父類children數組中,這樣一次遍曆即可形成樹形結構。  foreach($tree as $key=>$item){      if($item[‘pid‘] != 0){          $tree[$item[‘pid‘]][‘children‘][] = &$tree[$key];//注意:此處必須傳引用否則結果不對          if($tree[$key][‘children‘] == null){              unset($tree[$key][‘children‘]); //如果children為空白,則刪除該children元素(可選)          }      }  }  ////第三步,刪除無用的非根節點資料  foreach($tree as $key=>$category){      if($category[‘pid‘] != 0){          unset($tree[$key]);      }  }    print_r($tree);    /*======================遞迴實現========================*/  $tree = $categories;  function get_attr($a,$pid){      $tree = array();                                //每次都聲明一個新數組用來放子項目      foreach($a as $v){          if($v[‘pid‘] == $pid){                      //匹配子記錄              $v[‘children‘] = get_attr($a,$v[‘id‘]); //遞迴擷取子記錄              if($v[‘children‘] == null){                  unset($v[‘children‘]);             //如果子項目為空白則unset()進行刪除,說明已經到該分支的最後一個元素了(可選)              }              $tree[] = $v;                           //將記錄存入新數組          }      }      return $tree;                                  //返回新數組  }  echo "<br/><br/><br/>";    print_r(get_attr($tree,0));  

  

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.