【发布时间】:2015-10-14 03:37:34
【问题描述】:
所以我从一个多维数组中的 API 得到了很大的响应,我需要找到某个键-> 值对的所有实例,特别是 ['type'] => PhotoField 如果它们都是相同的深度,但它们有所不同,所以我使用递归函数来获取特定值的所有键值对。为了我的目的,我已经变形了一个标准的递归数组搜索算法。但是我仍然有一个问题,当它将每个实例的路径推送到$path 数组时,它只是合并到前一个实例的路径。
我真正需要的是让每个实例的路径成为$path 中的子数组。
这是我的功能:
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;
}
我称之为:
array_searchRecursive($resp['form']);
这里是一些示例数据:
$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
)
)
)
)
)
)
)
衷心感谢您的帮助。非常感谢。
【问题讨论】:
-
你能告诉我们你真正想要得到的结果吗?
标签: php arrays algorithm recursion