[英]Anonymous PHP function with in_array not working
I have this simple array $tree
in PHP that I need to filter based on an array of tags matching those in the array. 我在PHP中有一个简单的数组
$tree
,需要根据与数组中的标签匹配的标签数组进行过滤。
Array
(
[0] => stdClass Object
(
[name] => Introduction
[id] => 798162f0-d779-46b6-96cb-ede246bf4f3f
[tags] => Array
(
[0] => client corp
[1] => version 2
)
)
[1] => stdClass Object
(
[name] => Chapter one
[id] => 761e1909-34b3-4733-aab6-ebef26d3fcb9
[tags] => Array
(
[0] => pro feature
)
)
)
I tried using an anonymous function like so: 我尝试使用匿名函数,如下所示:
$selectedTree = array_filter($tree, function($array) use ($selectedTags){
return in_array($array->tags, $selectedTags, true);
});
$selectedTags: $ selectedTags:
Array
(
[0] => client corp
)
The above is returning empty when I'd expect item 1 to be returned. 当我希望返回项目1时,以上返回的是空的。 No error thrown.
没有引发错误。 What am I missing?
我想念什么?
In case of in_array($neddle, $haystack) . 如果是in_array($ neddle,$ haystack) 。 the
$neddle
must need to be a String
, but you're giving an array that is why its not behaving properly. $neddle
必须是一个String
,但是您给出一个数组,这就是为什么它不能正常运行的原因。
But if you like to pass array as value of $selectedTags
then you might try something like below: 但是,如果您希望将数组作为
$selectedTags
值传递,则可以尝试以下操作:
$selectedTree = array_filter($tree, function($array) use ($selectedTags){
return count(array_intersect($array->tags, $selectedTags)) > 0;
});
Ref: array_intersect 参考: array_intersect
If I am reading the question correctly, you need to look at each object in $tree
array and see if the tags property contains any of the the elements in $selectedTags
如果我正确阅读了该问题,则需要查看
$tree
数组中的每个对象,并查看tags属性是否包含$selectedTags
中的任何元素。
Here is a procedural way to do it. 这是一种程序上的方法。
$filtered = array();
foreach ($tree as $key => $obj) {
$commonElements = array_intersect($selectedTags, $obj->tags);
if (count($commonElements) > 0) {
$filtered[$key] = $obj;
}
}
I was going to also post the functional way of doing this but, see thecodeparadox's answer for that implementation. 我还将发布实现此功能的方法,但是请参阅该实现的codeparadox答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.