$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
.
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
. $x &= $y
is shorthand for$x = $x & $y
(bitwise AND). What you want isx = &$y
(assign by reference).
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
精彩评论