将平面数组转换为分层的多维数组

问题描述 投票:4回答:3

我有一个带有键-值对的标准数组-我想使用键将其转换为多维数组。困难似乎是我需要递归地循环未知数目的新键,并将它们转换为多维数组。简而言之,我想要这个:

$val[alfa.xray.uno] = "Some value";    
=> $val['alfa']['xray']['uno'] = "Some value";    

示例:(代码失败,并且还需要处理N个维度-但您知道了。)

$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";

print_r( array_flat_to_multidimensional($arr) );

function array_flat_to_multidimensional($arr) {
    foreach($arr as $key=>$val) {
        $key = explode(".",$key);
        for($i=0; $i<count($key); $i++) {
            if($i==0) { $out[$key[$i]] = $val; }
            else if($i==1) { $out[$key[$i-1]][$key[$i]] = $val; }
            else if($i==2) { $out[$key[$i-2]][$key[$i-1]][$key[$i]] = $val; }
            else if($i==3) { $out[$key[$i-3]][$key[$i-2]][$key[$i-1]][$key[$i]] = $val; }
        }
    }
    return $out;
}

也许RecursiveArrayIterator会成功吗?

php arrays recursion multidimensional-array
3个回答
7
投票

您可以使用引用来依次遍历并建立嵌套的数组结构:

$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;

2
投票

使用递归卢克

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);

1
投票

您可以在遍历数组层次结构级别时使用reference

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.