Reputation: 4539
I have a :
$value = "val";
I also have an array :
$keys = ['key1', 'key2', 'key3'...]
The keys in that array are dynamically generated, and can go from 2 to 10 or more entries.
My goal is getting this :
$array['key1']['key2']['key3']... = $value;
How can I do that ?
Thanks
Upvotes: 0
Views: 2334
Reputation: 76395
The easiest, and least messy way (ie not using references) would be to use a recursive function:
function addArrayLevels(array $keys, array $target)
{
if ($keys) {
$key = array_shift($keys);
$target[$key] = addArrayLevels($keys, []);
}
return $target;
}
//usage
$keys = range(1, 10);
$subArrays = addARrayLevels($keys, []);
It works as you can see here.
How it works is really quite simple:
if ($keys) {
: if there's a key left to be added$key = array_shift($keys);
shift the first element from the array$target[$key] = addArrayLevels($keys, []);
: add the index to $target
, and call the same function again with $keys
(after having removed the first value). These recursive calls will go on until $keys
is empty, and the function simply returns an empty arrayThe downsides:
The pro's:
$target
as a sort of default/final assignment variable, with little effort (will add example below if I find the time)Example using adaptation of the function above to assign value at "lowest" level:
function addArrayLevels(array $keys, $value)
{
$return = [];
$key = array_shift($keys);
if ($keys) {
$return[$key] = addArrayLevels($keys, $value);
} else {
$return[$key] = $value;
}
return $return;
}
$keys = range(1, 10);
$subArrays = addARrayLevels($keys, 'innerValue');
var_dump($subArrays);
Upvotes: 6
Reputation: 9765
I don't think that there is built-in function for that but you can do that with simple foreach
and references.
$newArray = [];
$keys = ['key1', 'key2', 'key3'];
$reference =& $newArray;
foreach ($keys as $key) {
$reference[$key] = [];
$reference =& $reference[$key];
}
unset($reference);
var_dump($newArray);
Upvotes: 5