如何动态访问可变多维数组中的值
$first = array("a", "b" => array("c", "d" => array("e", "f")), "g", "h" => array("f"));
$second = array("b", "d", "f");
$string = "foobar";
给定上面的代码,如何将 $first
中定义于 $second
的索引处的值设置为 $string
的内容?意思是,对于这个例子,它应该是 $first["b"]["d"]["f"] = $string;
,但是 $second
和 $first
可以是任意长度。然而,$second
始终是一维的。这是我尝试过的方法,它似乎没有按计划工作:
$key = "";
$ptr = $first;
for($i = 0; $i < count($second); $i++)
{
$ptr &= $ptr[$second[$i]];
$key = key($ptr);
}
$first[$key] = $string;
这将执行 $first["f"] = $string;
而不是正确的多维索引。我原以为使用 key
会找到数组中的位置,包括它已经向下移动的级别。
如何动态访问正确的密钥?如果维度数是静态的,我可以解决这个问题。
编辑:另外,我想要一种不使用 eval
的方法。
$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
? Meaning, for this example, it should be $first["b"]["d"]["f"] = $string;
, but the contents of $second
and $first
can be of any length. $second
will always be one dimensional however. 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;
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.
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
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际情况比这要复杂一些。如果每个级别尚不存在,则必须对其进行初始化。但您的实际问题是:
$ptr
中,而不是位于$first
中。$x &= $y
是$x = $x & 的简写形式。 $y
(按位与)。您想要的是x = &$y
(通过引用分配)。这应该可以做到:
用法:
DEMO
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:
$ptr
, not in$first
.$x &= $y
is shorthand for$x = $x & $y
(bitwise AND). What you want isx = &$y
(assign by reference).This should do it:
Usage:
DEMO