[英]Find values into Array of Object PHP
Hi I have this array of object嗨,我有这个对象数组
[
{
"id": 1,
"categories": [
222,
243,
208,
115,
173,
253,
236,
121,
69,
250,
221,
270,
245,
123,
124
]
},
{
"id": 2,
"categories": [
222,
243,
208,
69,
250,
221,
270,
245,
123,
124
]
},{
"id": 8774,
"categories": [
222,
243,
208,
115,
173,
253,
236,
121
]
}
]
I want to search in the "categories" array of all objects values in other array and print the match.我想在其他数组中所有对象值的“类别”数组中搜索并打印匹配项。
Example, I want search the values 222
and 121
, values that I push in array例如,我想搜索值
222
和121
,我推入数组的值
$array = ("222","121");
And I want search this two values in the result, and print only the object id = 1 and 8774 because are the ones that coincides.我想在结果中搜索这两个值,并只打印对象 id = 1 和 8774,因为它们是重合的。
I tested with array_filter into a foreach but doenst works!我用 array_filter 在 foreach 中进行了测试,但确实有效! Any idea?
任何的想法? Thanks
谢谢
This my code这是我的代码
$search = array("231","228");
$result = array_filter($array, function ($item) use ($search) {
if (array_intersect($item["categories"], $search)) {
return true;
}
return false;
});
//$array is the array of object result
Array_intersect works but I need print only the Objects that contains the values into a "search" array. Array_intersect 有效,但我只需要将包含值的对象打印到“搜索”数组中。 Considering that the "search" array can have more than two values
考虑到“搜索”数组可以有两个以上的值
array_intersect($array1, $array2)
will be truthy if there are any matches between the two arrays.如果两个数组之间有任何匹配,则 array_intersect
array_intersect($array1, $array2)
将是真实的。 It looks like you only want to select the items that have all the categories in $search
.看起来您只想选择具有
$search
所有类别的项目。 To test that, you need to use要测试它,您需要使用
if (count(array_intersect($item["categories"], $search)) == count($search))
Also, in general there's no point in writing此外,一般来说,写作是没有意义的
if (condition) {
return true;
} else {
return false;
}
Just write:写就好了:
return condition;
So it looks like:所以它看起来像:
$result = array_filter($array, function ($item) use ($search) {
return count(array_intersect($item["categories"], $search)) == count($search);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.