Transform flat array into a hierarchical, multi-dimensional array

后端 未结 3 980
孤城傲影
孤城傲影 2021-01-18 19:11

I have a standard array with key-value pairs - and I want to use the keys to transform it into a multi-dimensional array. The difficulty seems to be that I need to loop recu

3条回答
  •  遥遥无期
    2021-01-18 19:44

    You can use a reference while walking though the array hierarchy levels:

    function array_flat_to_multidimensional($arr) {
        $out = array();
        foreach ($arr as $compoundKey => $val) {
            $ref = &$out;
            foreach (explode(".", $compoundKey) as $key) {
                if (!array_key_exists($key, $ref)) $ref[$key] = array();
                $ref = &$ref[$key];
            }
            $ref = $val;
        }
        unset($ref);
        return $out;
    }
    

提交回复
热议问题