This question already has an answer here:
I have a little problem. Here is my array:
$data = array(
'properties'=>array{
[0]=>
array {
["name"]=>"prop1",
["properties"]=>
array {
[0]=>
array(5) {
["name"]=>"sub_prop1"
}
[1]=>
array(6) {
["name"]=>"sub_prop2",
["properties"]=>
array(2) {
[0]=>
array(6) {
["name"]=>"MARK"
}
}
}
}
},
[1]=>
array {
["name"]=>"prop2"
}
}
);
Array path is: 0/1/0. I know all the keys until array with name "Mark", I need a recursive function to get out this array equivalent with this: $data['properties'][0]['properties][1][properties][0]. Please help me!!!
</div>
I would use references instead of recursion, but maybe someone will answer with a recursive function. If you know the name
key then put it in the path. If not then the reset
will get the first item:
$path = array('properties', 0, 'properties', 1, 'properties', 0);
$result =& $data;
foreach($path as $key) {
$result =& $result[$key];
}
echo reset($result);
// or if you want array('name' => 'MARK')
print_r($result);
I found also this solution:
function get_array_by_key_path($data, $key_path){
if(count($key_path) == 0){
return $data;
}
$key = array_shift($path_keys);
// and recursion now
return get_array_by_key_path($data['properties'][$key], $keys);
}