php遞歸獲取無限分類菜單

從數據庫獲取全部菜單信息,須要根據id,pid字段獲取主菜單及其子菜單,以及子菜單下的子菜單,能夠經過函數遞歸來實現。php

<?php 
class Menu {
    public $menu = array(
      array('id'=>1,  'title'=>"一級1",'pid'=>0),
     array('id'=>2,  'title'=>"一級2",'pid'=>0),
     array('id'=>3,  'title'=>"二級11",'pid'=>1),
     array('id'=>4,  'title'=>"二級12",'pid'=>1),
     array('id'=>5,  'title'=>"二級21",'pid'=>2),
        array('id'=>6,  'title'=>"二級22",'pid'=>2),
     array('id'=>7,  'title'=>"三級1",'pid'=>3),
     array('id'=>8,  'title'=>"三級2",'pid'=>3),
       );

    public function __construct() {
         return $this->getMenu();
    }
    /**
     * 主菜單pid爲0
     * @return array
     */     
    protected function getMenu() {
        foreach ($this->menus as $key => $items) {
            if ($items['pid'] == "0" ) {
                unset($this->menu[$key]);
                $menu[] = $this->buildMenuTree($items, $items['id']);
            }
        }
        return $menu;
    }
    /**
     * 生產多級菜單樹
     * @param array $items
     * @param int $rid
     * @return array
     */
    protected function buildMenuTree($items,$rid) {
        $childs = $this->getChildMenu($items, $rid);
        if (isset($childs['child'])) {
            foreach ($childs['child'] as $key => $value) {
                $children = $this->buildMenuTree($value, $value['id']);
                if (null != $children['child']) {
                    $childs['child'][$key]['child'] = $children['child'];
                }
            }
        }
        return $childs;
    }
    
    /**
     * 獲取子菜單
     *
     */
    protected function getChildMenu($items,$rid) {
        foreach ($this->menu as $key => $value) {
            if ($value['pid'] == $rid) {
                unset($this->menu[$key]);
                $items['child'][] = $value;
            }
        }
        return $items;
    }
    
}


var_dump(new Menu);        

 

 

 


測試結果爲:
array(2) {
  [0] => array(4) {
    ["id"] => int(1)
    ["title"] => string(7) "一級1"
    ["pid"] => int(0)
    ["child"] => array(2) {
      [0] => array(4) {
        ["id"] => int(3)
        ["title"] => string(8) "二級11"
        ["pid"] => int(1)
        ["child"] => array(2) {
          [0] => array(3) {
            ["id"] => int(7)
            ["title"] => string(7) "三級1"
            ["pid"] => int(3)
          }
          [1] => array(3) {
            ["id"] => int(8)
            ["title"] => string(7) "三級2"
            ["pid"] => int(3)
          }
        }
      }
      [1] => array(3) {
        ["id"] => int(4)
        ["title"] => string(8) "二級12"
        ["pid"] => int(1)
      }
    }
  }
  [1] => array(4) {
    ["id"] => int(2)
    ["title"] => string(7) "一級2"
    ["pid"] => int(0)
    ["child"] => array(2) {
      [0] => array(3) {
        ["id"] => int(5)
        ["title"] => string(8) "二級21"
        ["pid"] => int(2)
      }
      [1] => array(3) {
        ["id"] => int(6)
        ["title"] => string(8) "二級22"
        ["pid"] => int(2)
      }
    }
  }
}
相關文章
相關標籤/搜索