简体   繁体   English

如何动态访问可变多维数组中的值

[英]How to dynamically access values in a variably multidimensional array

$first = array("a", "b" => array("c", "d" => array("e", "f")), "g", "h" => array("f"));
$second = array("b", "d", "f");
$string = "foobar";

Given the above code, how can I set a value in $first at the indexes defined in $second to the contents of $string ? 鉴于上面的代码,我怎样才能在$second定义的$first中设置一个值$string的内容? Meaning, for this example, it should be $first["b"]["d"]["f"] = $string; 意思是,对于这个例子,它应该是$first["b"]["d"]["f"] = $string; , but the contents of $second and $first can be of any length. ,但$second$first的内容可以是任意长度。 $second will always be one dimensional however. 然而, $second总是一维的。 Here's what I had tried, which didn't seem to work as planned: 这是我尝试过的,似乎没有按计划运行:

$key = "";
$ptr = $first;
for($i = 0; $i < count($second); $i++)
{
    $ptr &= $ptr[$second[$i]];
    $key = key($ptr);
}
$first[$key] = $string;

This will do $first["f"] = $string; 这将是$first["f"] = $string; instead of the proper multidimensional indexes. 而不是适当的多维索引。 I had thought that using key would find the location within the array including the levels it had already moved down. 我原以为使用key会找到数组中的位置,包括它已经向下移动的级别。

How can I access the proper keys dynamically? 如何动态访问正确的密钥? I could manage this if the number of dimensions were static. 如果尺寸的数量是静态的,我可以管理这个。

EDIT: Also, I'd like a way to do this which does not use eval . 编辑:另外,我想要一种不使用eval

It's a bit more complicated than that. 这比那复杂一点。 You have to initialize every level if it does not exist yet. 如果尚未存在,则必须初始化每个级别。 But your actual problems are: 但你的实际问题是:

  • The array you want to add the value to is in $ptr , not in $first . 要添加值的数组是$ptr ,而不是$first
  • $x &= $y is shorthand for $x = $x & $y (bitwise AND). $x &= $y$x = $x & $y (按位AND)的简写。 What you want is x = &$y (assign by reference). 你想要的是x = &$y (通过引用分配)。

This should do it: 这应该这样做:

function assign(&$array, $keys, $value) {
    $last_key = array_pop($keys);
    $tmp = &$array;
    foreach($keys as $key) {
        if(!isset($tmp[$key]) || !is_array($tmp[$key])) {
            $tmp[$key] = array();
        }
        $tmp = &$tmp[$key];
    }
    $tmp[$last_key] = $value;
    unset($tmp);
}

Usage: 用法:

assign($first, $second, $string);

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM