php简单的实现无限级分类-递归

递归
数据库
在这里插入图片描述
递归的思路就是【找sons】,也就是循环所有数据,找到每条数据的所有sons、sons的sons、sons的sons的sons…,首先我们知道要找test1的sons就是找所有pid为1的数据,于是遍历整个数组找到了test1-1和test1-2;然后还要分别找test1-1和test1-2的sons,就这样一直找下去,由于每次找sons的方法都是一样的,就是遍历所有数据(除开自己的父级,因为父级不可能是sons),找出符合条件的,唯一不同的就是每次找sons的父级不一样,代码如下:

//查到数据
public function CourseCategoryList(){
$list = DB::connection(‘sqlsrv’)->table(‘demo’)
->select(‘Fid’,‘FCategoryName’,‘FParentID’)
->get()->toArray();
t e m p = [ ] ; f o r e a c h ( temp = []; foreach ( temp=[];foreach(list as $key => KaTeX parse error: Expected '}', got 'EOF' at end of input: … if (comment->FParentID == 0) {
unset( l i s t [ list[ list[key]);
$comment->childrenList = t h i s − > g e t S u b T r e e ( this->getSubTree( this>getSubTree(list, $comment->Fid);
$temp[] = $comment;
}
}
return $this->_response([‘list’ => $temp]);
}

public function _getSubTree($list, $pid){
c h i l d = [ ] ; / / 循 环 所 有 数 据 找 child = []; //循环所有数据找 child=[];//id的sons
foreach ($list as $key => KaTeX parse error: Expected '}', got 'EOF' at end of input: … if (datum->FParentID == KaTeX parse error: Expected 'EOF', got '&' at position 5: pid &̲&datum->FParentID >0) {
//先去掉自己,自己不可能是自己的sons
unset( l i s t [ list[ list[key]);
//递归找,并把找到的sons放到一个child的字段中
$datum->childrenList = t h i s − > g e t S u b T r e e ( this->_getSubTree( this>getSubTree(list, $datum->Fid);
$child[] = $datum;
}
}
return $child;
}

返回如下:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值