function listToTree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0) {
    $tree = array();
    if (is_array($list)) {
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[ $data[ $pk ] ] = &$list[ $key ];
        }

        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[ $pid ];

            if ($root == $parentId) {
                $tree[ $data[ $pk ] ] = &$list[ $key ];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[ $parentId ];
                    $parent[ $child ][ $data[ $pk ] ] = &$list[ $key ];
                    
                    $parent[ $child ] = array_values($parent[ $child ]);
                }
            }
        }
    }

    return $tree;
}

 

posted on 2020-06-03 20:32  夏沫忆香  阅读(1841)  评论(0编辑  收藏  举报