【问题标题】:How to turn an array of paths into a multi dimensional array of varying depth?如何将路径数组变成不同深度的多维数组?
【发布时间】:2016-01-14 13:32:27
【问题描述】:

我想转成这样的路径数组:

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

路径数组可以包含任意深度的路径,可以是键值对,也可以是通过索引访问的普通数组。我已经尝试过递归,但不能完全弄清楚这一点,即使我觉得解决方案会很短。有任何想法吗?

【问题讨论】:

  • 45 值发生了什么变化? x 键不应该以[4, 5] 结尾,所以0=41=5
  • 'x/y/0' => 4 和 'x/y/1' => 5 意味着 'x' => 'y' => 的值是一个数组,而不是一个映射/键值对。谈论这种事情让我希望这两个东西在 PHP 中有不同的名称,而不是它们都被称为“数组”
  • 但是'x/y/0'x/y/1 中的45 值发生了什么变化?它们只是消失了,不再存在于建议的输出中。 x/y/0/test 会被如何对待?此外,您确实意识到,如果您要对输出进行 json_encode,则具有从零开始的连续数字键的数组将转换为 JS 数组,而不是对象([],而不是 {})。如果您只想丢失值(=> 的右侧)并将键中的最后一个值作为附加到输出的值,您可以在下面的代码中执行此操作。这是一个简单的测试。

标签: php recursion multidimensional-array


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-06-03
    • 2018-02-12
    • 2012-06-26
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多