PHP递归实现无限极分类
摘要
今天在编码的时候要用到二级的栏目分类,所以顺便就把无限极分类给整理了一下,采用的是递归方法
//实现无限级分类
public function getTree()
{
$categorys = Category::all();
return $this->makeTree($categorys, 'cate_id', 'cate_pid', 'cate_name', 0);
}
public function makeTree($list, $pk = 'id', $pid = 'pid', $child = 'child', $root = 0)
{
$tree = array();
foreach ($list as $key => $val) {
if ($val[$pid] == $root) {
//获取当前$pid所有子类
unset($list[$key]);
if (!empty($list)) {
$tmpChild = self::makeTree($list, $pk, $pid, $child, $val[$pk]);
if (!empty($tmpChild)) {
$val['_' . $child] = $tmpChild;
}
}
$tree[] = $val;
}
}
return $tree;
}
效果如下