Here is my precode...
$keys = array('a', 'b', 'c', 'd');
$number = 10;
And here is my code...
eval('$array[\''.implode('\'][\'',$keys).'\'] = $number;');
Using this, I get the following result...
Array (
[a] => Array
(
[b] => Array
(
[c] => Array
(
[d] => 10
)
)
)
)
Now, the problem is that this is the exact result I want, but I don't want to use eval()
.
As input to my code, I have a list of keys
and a number
. The number
should be set to the value of the keys
array being used to generate child-based keys
for a certain array $array
.
Is there a different way that I can achieve this? I don't want to overwrite the keys/numbers with new values as the code works - eval()
preserves this already, so my new code should do the same.
Here is a full code example showing how it would work. Whats important is that you use a reference to the array so you can modify it:
<?php
$keys = array('a', 'b', 'c', 'd');
$number = 10;
$org_array = array(
"a" => "string",
"z" => array( "k" => false)
);
function write_to_array(&$array, $keys, $number){
$key = array_shift($keys);
if(!is_array($array[$key])) $array[$key] = array();
if(!empty($keys)){
write_to_array($array[$key], $keys, $number);
} else {
$array[$key] = $number;
}
}
write_to_array($org_array, $keys, $number);
print_r($org_array);
?>
Please note that the code below (which you evaluate) will generate a warning, and will therefore not work on projects with error reporting up to the max:
$array = array();
$array['a']['b'] = 42; // $array['a'] is not an array... yet
Since you're using PHP 5, you can work with references to manipulate your array while traversing the branch of your tree that you wish to modify.
$current = & $array;
foreach ($keys as $key):
if (!isset($current[$key]) || !is_array($current[$key]))
$current[$key] = array();
$current = & $current[$key];
endforeach;
$current = $value;
Edit: corrected for avoiding warnings and conflicts.
function deepmagic($levels, $value)
{
if(count($levels) > 0)
{
return array($levels[0] => deepmagic(array_slice($levels, 1),
$value));
}
else
{
return $value;
}
}
$a = deepmagic(Array('a', 'b', 'c', 'd'), 10);
var_dump($a);
Output:
array(1) {
["a"]=>
array(1) {
["b"]=>
array(1) {
["c"]=>
array(1) {
["d"]=>
int(10)
}
}
}
}