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