php实现数据树形结构 递归方法

2017-09-13 12:25:47来源:CSDN作者:genziisme人点击

分享
//2.定义递归查询 数据格式化    public function data($pid=0){        $data = /DB::table('types')->where('pid',$pid)->get();        foreach ($data as $key=>$val){            $val->zi = $this->data($val->id);        }        return $data;    }    //3.递归查询 数据格式化    public function data1($data,$pid=0){        $newArr = array();        //获取顶级分类        foreach ($data as $key=>$val){            if ($val->pid == $pid){                $newArr[$val->id] = $val;                $newArr[$val->id]->zi = $this->data1($data,$val->id);            }        }        return $newArr;    }    public function index()    {        //1.使用面向过程方式实现树层 (淘汰)        $one = /DB::table('types')->where('pid',0)->get();        foreach ($one as $value){            $value->zi = /DB::table('types')->where('pid',$value->id)->get();        }        foreach ($one as $value){            foreach ($value->zi as $v){                $v->zi = /DB::table('types')->where('pid',$v->id)->get();            }        }        //2.使用递归实现数据格式化 (不建议使用,对数据库压力较大)        $arr = $this->data();        //3.递归实现数据格式化 ,优化2        $data = /DB::table('types')->get();        $arr = $this->data1($data,$pid=0);        //实现树形结构        $data = /DB::select('select types.*,concat(path,id) p from types order by p');        //查询数据//        $data = /DB::table('types')->orderBy('sort','desc')->get();        return view('admin.types.index',['data'=>$data]);    }

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台