生成树结构

/**生成树
     * @param $list
     * @return array
     */
    private function makeTree($list)
    {

         $tree = [];
         $data=[];
         //为了确保树结构数据完整,获取所有得层级
        foreach ($list as $k => $v) {
            if ($v['pid']!=0){
                $data = $this->getParent($v['pid'], $v);
            }
        }
        //组合树结构
        $list=array_merge($list,$data);
        $depth = array_column($list, 'id');
        $list = array_combine($depth, $list);
        foreach ($list as $k => $v) {
            if (isset($list[$v['pid']])) {
                $list[$v['pid']]['children'][] =& $list[$k];
            } else {
                $tree[] =& $list[$k];
            }
        }
        return $tree;
    }


    /**为了父级层级完整,获取上级数据
     * @param $pid
     * @param array $value
     * @return mixed
     */
    private function getParent($pid, $value = [])
    {
        static $data;
        $parent = Ability::where('id', $pid)->
        select('id', 'name', 'title', 'pid', 'lft', 'rgt', 'id as key', 'id as value', 'depth')->first();
        if ($parent) {
            $parent = $parent->toArray();
            $data[$value['id']] = $value;
            $this->getParent($parent['pid'], $parent);
        }else if (!isset($data[$value['id']])){
            $data[$value['id']]=$value;
        }
        return $data;
    }

 

你可能感兴趣的:(php)