Given the following array of key names in the following format (number of fields can change):
$field_names = Array
(
[0] => web
[1] => results
[2] => result
[3] => title
)
I'd like to access the 'content' key value of the following multi-leveled array:
$values=stdClass Object(
[web] => Array(
[results] => Array(
[result] => Array(
[title] => Array(
[type] => default
[content] => Sample content
)
)
)
)
)
Sample example how value can be accessed given above arrays:
$value = $values->{$field_names[0]}[$field_names[1]][$field_names[2]][$field_names[3]]['content'];
For the sake of simplicity (keep it plain PHP), I won't get into much details as the existing code is part of some handler which is part of some plugin which is part of some module which is part of another module which is part of content management system in order to parse YQL results, but its logic is broken.
The code looks like:
$field = array_shift($field_names);
$value = $values->$field;
foreach ($field_names as $field) {
if (is_array($value)) {
$value = $value[$field];
}
}
I've tried to do a dirty patch like:
$value = is_string($value[$field]) ? $value[$field] : $value[$field]['content'];
And it worked for one example, but it doesn't work for all cases, like one above.
I'm aware of recursive functions and array_walk_recursive()
, but I'd like to avoid headache of using them in order to make it simple as possible.
Is there any simple way of accessing value of multi-leveled array having dynamic array of key names?