Laravel使用array_diff获取两个数组差集返回空数组的问题排查
问题原因及修复方案
- 核心错误为
array_diff函数的参数传值顺序颠倒:
PHP原生array_diff函数的作用是返回第一个参数数组中,不存在于后续所有参数数组中的元素,你当前的需求是获取$hamkor_products数组中不存在于$product_list数组的值,原有代码array_diff($product_list, $hamkor_products)是查询$product_list的独有元素,结合你运行截图里的数组内容,$product_list的所有元素都在$hamkor_products中存在,自然返回空数组。 - 修复代码只需调换两个数组的参数顺序即可:
$product_list = Operation::where('kvit_id', $kvit->id)->pluck('product_id')->toArray(); $hamkor_products = ListProduct::where('user_id', $newkvit->user_id)->pluck('product_id')->toArray(); // 调换参数顺序,查询$hamkor_products中不存在于$product_list的元素 $operProductList = array_diff($hamkor_products, $product_list); dd($product_list, $hamkor_products, $operProductList);
- 额外注意事项:
array_diff执行的是带类型的等值判断,如果两个数组中product_id的类型不一致(例如一个为字符串、一个为整型),会出现数值相同但被判定为不同的情况,这种场景可以先统一转换数组元素类型再计算差值:
$product_list = array_map('intval', Operation::where('kvit_id', $kvit->id)->pluck('product_id')->toArray()); $hamkor_products = array_map('intval', ListProduct::where('user_id', $newkvit->user_id)->pluck('product_id')->toArray()); $operProductList = array_diff($hamkor_products, $product_list);
内容的提问来源于stack exchange,提问作者Hayrulla Melibayev
相关产品推荐
相关产品推荐

