Let's say I have a multidimensional array like this :
$array = array(
'first' => array(
'second' => array(
'last1' => array(
'key1' => 'value1',
'key2' => 'value2',
),
'last2' => array(
'key3' => 'value3',
'key4' => 'value4',
),
),
),
);
To retrieve the value of the key key1
of the sub array last1
, I would use:
$value = $array['first']['second']['last1']['key1'];
// Output value1
In my real use case, I need to retrieve the value of key1
from the following string:
$param = 'first.second.last1.key1';
I convert it to an array of keys in the good order:
$keys = explode('.', $param);
// Output array('first', 'second', 'last1', 'key1')
To retrieve the value after exploding the keys, I use the following method:
function get_value_from_keys(array $array, array $keys) {
$lastKey = $keys[count($keys) - 1];
foreach ($keys as $key) {
$newArray = $newArray[$key];
if ($key == $lastKey) {
break;
}
}
return $newArray;
}
get_value_from_keys($array, $keys);
// Output value1
But now, I need to set the value, also the question is:
How can I change the value of key1
dynamically, without hard-coding the keys ?
I cannot use the same logic as get_value_from_keys
without squashing the array during the loop.