多维数组中的部分搜索不适用于深度元素

Partial search in multidimensional array not working in depth elements

你好,我从 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 值(例如 Potter)时,它正在工作。但是当涉及到 artistcountry 时。我的代码不再起作用了。搜索将 return 所有匹配项。 以下是我到目前为止所做的:

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 的许多循环和内置函数的使用。我只想要一个简单但有效的解决方案。希望有人会分享一些想法。谢谢

您需要将对 searchFor 的递归调用结果与结果 $r 合并。尝试在 else 语句中递归调用 searchFor:

else {
    $r = array_merge($r, searchFor($array['country'],$needle));
}

以下逻辑可能对您有所帮助:

$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
            }
        }
    }
}

工作demo