I have a given path with keys (in a separate array) to a subarray within a multidimensional one.
$path_array = array( 'first', 'new', 'best');
$multi_data = array(
'first' => array(
'example' => 'good',
'other' => 'well',
'new' => array(
'subset' => 'none',
'best' => 'stackoverflow',
)
)
);
The arrays are changing of course due to dynamically generated data.
My Question: How to get the correct value or array by the path that i have got?
A correct static approach would be:
echo $multi_data['first']['new']['best'];
// prints: stackoverflow
I tried foreach-Loop on $path_array, but i cant put the path elements together (keys is square brackets).
2
Answers
EDIT: don’t know why I went through all this trouble with shifting values, foreach works just fine
Could do something like:
The idea is to get deeper into the array with each iteration. Be extra careful if you might have some non-existent keys, though.
I suggest this recursive function:
demo
Note that the first parameter
&$arr
is a reference to the data array to avoid a copy of the array at each call of the function. But the final return (the string"stackoverflow"
in your example) is a copy. In other words, if you call the function like that:and then you change the value of
$result
:the value inside the array doesn’t change.
But if you want the function returns a reference (useful to edit the array data), you have to change the function declaration like that:
and to also call it with an ampersand:
This time, if you change
$result
, it will also change the value in the array, because it’s no more a copy but a reference to the data in the array.demo