如何在两个Laravel集合对象中查找常见项目



我试图比较两个集合,并将两者中存在的所有值放入另一个集合中。

因此,给定这些集合:

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

我想提取"奶酪"one_answers"面包">

在这种情况下,您需要交集方法:

intersect方法从原始集合中删除给定数组或集合中不存在的任何值。生成的集合将保留原始集合的密钥:

$text1Collection = collect('burger', 'cheese', 'bread', 'ham');
$text2Collection = collect('cheese', 'bread', 'tomato');
$resultCollection =$text1Collection->intersect($text2Collection);

您希望intersect方法在Collections:上可用

$intersect = $text1->intersect($text2);
$intersect->all(); // [1 => 'cheese', 2 => 'bread']

最新更新