laravel通用版分类递归,多级

1.我是把这个多级递归放在了model,你可以放在service层,或其他,只要你控制器能够调用到  


//一般传进三个参数。默认P_id=0;
public function getTree($data,$field_name,$field_id='id',$field_pid='pid',$pid=0)
{
    $arr = array();
    foreach ($data as $k=>$v){
        if($v->$field_pid==$pid){
            $data[$k]["_".$field_name] = $data[$k][$field_name];
            $arr[] = $data[$k];
            foreach ($data as $m=>$n){
                if($n->$field_pid == $v->$field_id){
                    $data[$m]["_".$field_name] = '├─ '.$data[$m][$field_name];
                    $arr[] = $data[$m];
                }
            }
        }
    }
    return $arr;
}

通用版多级递归方法(新改造)

//需要注意的是,$list数组的格式,是否符合递归的要求  
  function array_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $list[$key][$child] = [];
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }

 

你可能感兴趣的:(PHP)