Transform flat array into a hierarchical, multi-dimensional array

后端 未结 3 975
孤城傲影
孤城傲影 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;
    }
    
    0 讨论(0)
  • 2021-01-18 19:50

    use the recursion Luke

    function ins(&$ary, $keys, $val) {
        $keys ? 
            ins($ary[array_shift($keys)], $keys, $val) :
            $ary = $val;
    }
    
    // test
    
    $arr['alfa.xray.uno'] = "Alfa X-Ray Uno";
    $arr['alfa.yaho.duo'] = "Alfa Yaho Duo";
    $arr['beta.xray.uno'] = "Beta X-Ray Uno";
    $arr['beta.xray.duo'] = "Beta X-Ray Duo";
    $arr['just-me'] = "Root-level item";
    
    $a = array();
    foreach($arr as $k => $v)
        ins($a, explode('.', $k), $v);
    
    print_r($a);
    
    0 讨论(0)
  • 2021-01-18 19:53

    You could use references to successively iterate through and build up the nested array structure:

    $out = array();
    foreach ($arr as $key=>$val) {
        $r = & $out;
        foreach (explode(".", $key) as $key) {
            if (!isset($r[$key])) {
                $r[$key] = array();
            }
            $r = & $r[$key];
        }
        $r = $val;
    }
    return $out;
    
    0 讨论(0)
提交回复
热议问题