1. 程式人生 > >PHP遞迴獲取選單

PHP遞迴獲取選單

//首先做一個類內的變數,儲存一下相關的陣列:
 public $tree = null;
 //然後做個測試方法,用於輸出結果
 public function test() {
        $res = M('channel')->where('fatherid is null')->select();
        $this->createtree($res);
        dump($this->tree);
 }
 //這裡是遞迴方法
 private function createtree(array $data = null, $lv = 1) {
        for ($i = 0; $i < count($data); $i++) {
            $data[$i]['lv'] = $lv;
            $this->tree[count($this->tree)] = $data[$i];
            $res = M('channel')->where('fatherid='.$data[$i]['cid'])->select();
            $this->createtree($res, ($lv + 1));
        }
 }