二维数组转树形结构数组

function list_to_tree($list, $pk = 'id', $pid = 'parent_id', $child = 'child', $root = 0)
{
    //创建Tree
    $tree = array();
    if (is_array($list)) {
        //创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }

        foreach ($list as $key => $data) {
            //判断是否存在parent
            $parantId = $data[$pid];
            if ($root == $parantId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parantId])) {
                    $parent = &$refer[$parantId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

你可能感兴趣的:(二维数组转树形结构数组)