一段完美的无限级分类递归
//获取树
public function tree()
{
$pid = $this->request->get('pid/d', 0);
$step = $this->request->get('step/d', 0);
$cutIds = $this->request->get('cut_ids/s', '');
$cutIds = explode(',', $cutIds);
$tree = ModelCate::getTree($pid, $step, $cutIds);
$this->result(200, $tree);
}
/**
* 获取分类树
* @param integer $pid 不传默认为0,即从根开始,传了值则从该类目开始往下获取。
* @param integer $step 递归层级,传入0或大于实际层级的数字则一直找到末级
* @param array $cutIds 从返回的树结构中砍掉指定id的分支,可传入多个id
* @return array
*/
public static function getTree($pid, $step, $cutIds = [])
{
$row = [];
$step--;
$childs = self::where([['pid', '=', $pid], ['id', 'not in', $cutIds]])->field('id,pid,title')->select();
foreach ($childs as $key => $value) {
if($step){
$value['children'] = self::getTree($value['id'], $step, $cutIds);
}
$row[] = $value;
}
return $row;
}
进一步减化,只用8行:
public static function getTree($pid, $step, $cutIds = [])
{
$row = [];
$step--;
$childs = self::where([['pid', '=', $pid], ['id', 'not in', $cutIds]])->field('id,pid,title')->select();
foreach ($childs as $key => $value) {
$value['children'] = $step ? self::getTree($value['id'], $step, $cutIds) : [];
$row[] = $value;
}
return $row;
}
进一步减化,只用6行:
public static function getTree($pid, $step, $cutIds = [])
{
$step--;
$rows = self::where([['pid', '=', $pid], ['id', 'not in', $cutIds]])->field('id,pid,title')->select();
foreach ($rows as $key => $value) {
$rows[$key]['children'] = $step ? self::getTree($value['id'], $step, $cutIds) : [];
}
return $rows;
}