You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在两个Laravel Collection集合对象中提取共同存在的元素

你可以直接使用Laravel集合内置的intersect()方法提取两个集合的公共元素,该方法会自动匹配值相同的项返回新的集合。

示例实现代码:

$text1 = collect(['burger', 'cheese', 'bread', 'ham']);
$text2 = collect(['cheese', 'bread', 'tomato']);

// 获取交集,返回的集合默认保留原集合的键名
$common = $text1->intersect($text2);

// 如果需要重置为连续的数字索引,可以链式调用values()方法
$common = $text1->intersect($text2)->values();

上述代码执行后得到的$common集合就包含你需要的cheese和bread两个公共元素。

补充说明:intersect()方法也支持直接传入普通数组作为参数,不需要提前把对比内容转为集合。

内容的提问来源于stack exchange,提问作者Dave Hulst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:39:00