So I have a big response from an API in a multi-dimensional array, and I need to find all the instances of a certain key->value pair, specifically ['type'] => PhotoField
My task would be easy if they were all the same depth, but they vary, so I am using a recursive function to get all the key value pairs of a specific value. I have morphed a standard recursive array searching algorithm for my purposes. But I still have the problem that when it pushes the path of each instance to the $path
array, it just merges to the path of the previous instance.
What I really need is for each instance's path to be a subarray within $path
.
Here is my function:
function array_searchRecursive($needle, $haystack, $strict=false, $path=array() )
{
if(!array_key_exists('elements', $haystack)) {
return false;
}
foreach( $haystack['elements'] as $key => $val ) {
if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) {
$path = array_merge($path, array($key), $subPath);
return $path;
} elseif( (!$strict && $val['type'] == $needle) || ($strict && $val['type'] === $needle) ) {
$path[] = $val['key'];
}
}
if (!(empty($path))){
return $path;
}
return false;
}
I call it with:
array_searchRecursive($resp['form']);
And here is some sample data:
$resp =
Array
(
[form] => Array
(
[name] => Site Inspection
[elements] => Array
(
[0] => Array
(
[type] => Section
[key] => 86d2
[elements] => Array
(
[0] => Array
(
[type] => ChoiceField
[key] => 450c
)
)
)
[1] => Array
(
[type] => Section
[key] => 6021
[elements] => Array
(
[0] => Array
(
[type] => TextField
[key] => c8e5
)
[1] => Array
(
[type] => PhotoField
[key] => 01dd
[label] => Photos of Protective Structure
)
[2] => Array
(
[type] => PhotoField
[key] => 8e1c
[label] => Photos of Degradation to Protective Structures
)
)
)
[2] => Array
(
[type] => Section
[key] => 9335
[elements] => Array
(
[0] => Array
(
[type] => TextField
[key] => b614
)
[1] => Array
(
[type] => Repeatable
[key] => 6b00
(
[0] => Array
(
[type] => TextField
[key] => b646
)
[1] => Array
(
[type] => PhotoField
[key] => 9747
)
)
)
)
)
)
)
Sincere thanks for any help. It is greatly appreciated.