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

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


白衣非少年
浏览 161回答 2
2回答

守着星空守着你

您需要将递归调用的结果与searchFor您的 result 合并$r。在语句中尝试以下else递归调用searchFor:else&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;$r&nbsp;=&nbsp;array_merge($r,&nbsp;searchFor($array['country'],$needle)); }

largeQ

以下逻辑可能会帮助您:$result = []; // $result is container for matches - filled by reference$needle = 'Wander'; // the value we are looking forrecurse($data, $needle, $result);function recurse($haystack = [], $needle = '', &$result) {&nbsp; &nbsp; foreach($haystack as $key => $value) {&nbsp; &nbsp; &nbsp; &nbsp; if(is_array($value)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; recurse($value, $needle, $result);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(strpos($value, $needle) !== false) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result[] = $value; // store match&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}工作演示
打开App,查看更多内容
随时随地看视频慕课网APP