如何检查数组是否包含另一数组的值?array_intersect无返回问题排查
解决array_intersect()对比对象数组无结果的问题
我来帮你分析下问题所在,然后给出可行的解决方案:
问题原因
array_intersect() 默认是通过**松散相等(==)**来判断数组元素是否相同,但对于 stdClass 对象来说:
- 只有当两个对象是同一个实例,或者所有属性的键和值完全匹配时,才会被判定为相等。
- 你的两个数组里的对象是不同的实例(比如
#8、#6和$interests里的object(...)),哪怕interestId相同,也不会被array_intersect()识别为相等元素,所以返回空数组。
解决方案
根据你的需求,有两种常用的处理方式:
1. 提取interestId后再对比(推荐,简单高效)
既然你只需要判断两个数组中是否有相同的interestId,可以先用array_column()把对象数组转换成纯ID的数组,再用array_intersect():
// 从用户兴趣数组中提取所有interestId $userInterestIds = array_column($userInterests, 'interestId'); // 从目标兴趣数组中提取所有interestId $targetInterestIds = array_column($interests, 'interestId'); // 对比两个ID数组是否有交集 if (!empty(array_intersect($userInterestIds, $targetInterestIds))) { echo "found"; }
array_column() 可以直接提取对象的属性值,非常适合这种场景。
2. 使用自定义比较函数的array_uintersect()
如果需要保留原对象,或者有更复杂的对比逻辑,可以用array_uintersect()自定义比较规则:
// 自定义对比函数:根据interestId判断两个对象是否匹配 $intersection = array_uintersect($userInterests, $interests, function($objA, $objB) { // 用strcmp对比字符串类型的interestId,返回0表示相等 return strcmp($objA->interestId, $objB->interestId); }); if (!empty($intersection)) { echo "found"; }
这个方法会返回两个数组中interestId相同的对象集合,适合需要后续使用匹配对象的场景。
内容的提问来源于stack exchange,提问作者VirtusBB
相关产品推荐
相关产品推荐

