你好,我从 API 得到了这样的结果:$data = ["1" => [ "book" => "Harry Potter", "artist" => array("David", "Emma"), "country" => [ ["description" => "Wander"], ["description" => "Magic"] ]],"2" => [ "book" => "Science book", "artist" => array("Artist 1", "Melanie Hudson"), "country" => [ ["description" => "Physics"], ["description" => "Albert Einstein"] ]],"3" => [ "book" => "Bible", "artist" => array("Artist 1", "Pedro"), "country" => [ ["description" => "Love"], ["description" => "Respect"] ]],];我正在做的是使用 PHP 在多维数组中部分搜索字符串值。当我搜索值(例如波特)时它正在工作book。但当涉及到artist和时country。我的代码不再起作用了。搜索将返回所有匹配项。以下是我到目前为止所做的事情:function searchFor($haystack, $needle){$r = array();foreach($haystack as $key => $array) {$contains = false;foreach($array as $k => $value) { if (!is_array($value)) { if(stripos($value, $needle) !== false ) { $contains = true; } } else { searchFor($array['country'],$needle); } } if ($contains) { array_push($r,$array); } } return $r; }echo ("<pre>");print_r(searchFor($data,"Wander")); <--- Not working. but when I change it to Potter it will work.echo ("</pre>");任何关于如何改进我的代码的想法将不胜感激。注意:我试图减少 PHP 中许多循环和内置函数的使用。我只是想要一个简单但有效的解决方案。希望有人能分享一些想法。谢谢
2 回答
守着星空守着你
TA贡献1799条经验 获得超8个赞
您需要将递归调用的结果与searchFor
您的 result 合并$r
。在语句中尝试以下else
递归调用searchFor
:
else { $r = array_merge($r, searchFor($array['country'],$needle)); }
largeQ
TA贡献2039条经验 获得超7个赞
以下逻辑可能会帮助您:
$result = []; // $result is container for matches - filled by reference
$needle = 'Wander'; // the value we are looking for
recurse($data, $needle, $result);
function recurse($haystack = [], $needle = '', &$result) {
foreach($haystack as $key => $value) {
if(is_array($value)) {
recurse($value, $needle, $result);
} else {
if(strpos($value, $needle) !== false) {
$result[] = $value; // store match
}
}
}
}
工作演示
- 2 回答
- 0 关注
- 159 浏览
添加回答
举报
0/150
提交
取消