更改数组搜索函数以返回多个结果
我修改了一个函数,该函数搜索数组以在数组中找到值时返回父项。它可以很好地返回找到的第一个项目,但我希望它返回找到的所有项目。我想这是因为我立即返回数组,但我不确定如何更改它以使其“返回”并返回多个查找结果。
功能:
function in_array_r($needle, $haystack) {
foreach ($haystack as $item) {
if ($item === $needle || (is_array($item) && in_array_r($needle, $item))) {
return $item;
}
}
return false;
}
I modified a function that searches through an array to return the parent item if a value is found within the array. It works fine for returning the first item found but I want it to return all the items found. I presume it's because i'm returning the array right away but i'm not sure how to change it to make it "go back" and return multiple finds.
Function:
function in_array_r($needle, $haystack) {
foreach ($haystack as $item) {
if ($item === $needle || (is_array($item) && in_array_r($needle, $item))) {
return $item;
}
}
return false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无需立即返回,只需将 $item 附加到数组中即可。将
return false
替换为return $your_array
(包含您的项目的数组)。因此,$your_array 将包含与您的条件匹配的所有项目。Instead of returning right away, just append $item in an array. Replace
return false
withreturn $your_array
(the one containing your items). $your_array will therefore contain every item matching your condition.是的,一旦从函数返回,执行就完成了。当您已经知道它相当于 $needle 时,我不确定返回一个任意值的目的是什么。看起来它应该简单地返回 true。假设您确实修改了函数以添加存储匹配项的 $matches 数组。如果最终得到一个包含 3 个“foo”元素的数组,那么它的价值是什么?
Yes, once you return from a function, execution is complete. I'm not sure what the purpose of returning one arbitrary value serves, when you already know that it is equivalent to $needle. Seems like it should simply return true. Let's say you did modify the function to add a $matches array that you stored matches in. What would the value of that be to you to end up with an array that had 3 "foo" elements in it?
这是我最终修复它的最终代码。感谢您的快速解答:)
Here is the final code I ended up with to fix it. Thanks for the quick answers :)