如何将一组路径转换为不同深度的多维数组?

时间:2015-10-15 22:28:45

标签: php recursion multidimensional-array

我想要转换一系列路径,例如:

$foo = [
 'a/b' => 1,
 'a/c' => 2,
 'x/y/0' => 4,
 'x/y/1' => 5
]

进入多维数组,如下所示:

$foo = [
 'a' => [ 'b' => 1, 'c' => 2],
 'x' => [ 'y' => [0, 1]
]

路径数组可以包含任何路径深度,可以是键值对,也可以是索引访问的普通数组。我已尝试过递归,但无法解决这个问题,即使我觉得解决方案会很短。有任何想法吗?

1 个答案:

答案 0 :(得分:0)

您可以在不递归的情况下使用引用将更深层次(并创建新键)移动到输出数组中。像这样的东西会起作用:

function nest($arr){
    //our output array
    $out = array();

    //loop over the array and get each key/value
    foreach($arr as $k=>$v){
        //split the key
        $k = explode('/', $k);

        //create our first reference
        $tmp = &$out;

        //loop over the keys moving deeper into the output array
        foreach($k as $key){
            //if the key is not found
            if(!isset($tmp[$key])){
                //add it
                $tmp[$key] = array();
            }
            //get a reference to the sub-array
            $tmp = &$tmp[$key];
        }

        //here $tmp should be as far down the array as the value needs to be
        //set the value into the array
        $tmp = $v;
    }
    return $out;
}

演示:http://codepad.viper-7.com/unQukp