根据pid,使用递归构建树形数据
简单的列表请求:
/*
商品分类列表
请求方式:get
请求参数:无
*/
public function lists(){
if(!$this->request->isGet())$this->error('请求失败,请使用get请求');
$res = db('type')->select();
!$res? $this->error('请求失败',[]): $this->success('请求成功',$res);
}
拿到的数据:
数据表:
使用递归函数:
原理就是一个简单的递归,将其中的pid和id进行比对,先判断是否包含pid,若包含则再执行一遍函数,直到没有pid的存在,同时和id进行比对,若相同,则在当前数据项创建一个 children 属性用来存放pid相同的数据,以此来构建属性数据
public function lists(){
if(!$this->request->isGet())$this->error('请求失败,请使用get请求');
$res = db('type')->select();
!$res? $this->error('请求失败',[]) : $this->success('请求成功',['mneu'=>self::toTree($res,0)]);
}
// 树形数据
public function toTree( $admin_menu, $menu_pid){
$tree = [];
foreach ($admin_menu as $k => $v) {
if($v['pid'] == $menu_pid){
$childData = self::toTree($admin_menu,$v['id']);
if(count($childData)>0){
$v['children'] = self::toTree($admin_menu,$v['id']);
}
$tree[] = $v;
}
}
return $tree;
}
再请求:
用的时候只需改几个变量即可,基本上通用
ヾ( ̄▽ ̄)Bye~Bye~