PHP基礎 遞歸查詢

表結構

垃圾分類表:

 

分類內容表:

 

查詢代碼:

   //垃圾分類內容
    public function get_content()
    {
        //獲取當前分類id
        $id = I('get.id', '');
        $model = M();
        $sql = "select id,parent_id,path,content from rs_rubbish_content where cid = " . $id . " ";
        $res = $model->query($sql);     //查詢所有
        //回調函數
        $list = $this->data_format($res, 0, 0);
        $this->apiReturn($list, 0, "success");
    }
    //垃圾內容遞歸查詢
    private function data_format($arr, $level = 0, $id = 0)
    {
        $list = [];
        foreach ($arr as $vo) {
            if ($vo['parent_id'] == $id) {
                //$vo['rank']=$level;
                $temp_list = $this->data_format($arr, $level + 1, $vo['id']);
                if (!empty($temp_list)) {
                    $sort_arr = array_column($temp_list, 'sort');
                    array_multisort($sort_arr, SORT_ASC, $temp_list);
                }
                $vo['children'] = $temp_list;
                $list[] = $vo;
            }
        }
        return $list;
    }

查詢出來的結果:

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章