如何比较 laravel 中的两个 collections
how to compare two collections in laravel
亲爱的 Stack 溢出者,您好,
我正在尝试将一个 collection 与名称 'text1' 与另一个 collection 'text2'.
进行比较
我想实现它将 'text1' 和 'text2' 都具有的所有值放入另一个 collection.
我已经尝试过使用 Diff 和 DiffKeys(参见 compare two collection arrays in laravel)。
但我无法完全理解如何使用这些函数将 2 collection 的值相互比较。在我看来,这两个函数(Diff 和 DiffKeys)需要一个密钥,我(还)没有专门使用它来提取我的 collections.
的部分内容
我的 'text1' collection 看起来像这样:
$text1 = collect('burger', 'cheese', 'bread', 'ham');
我的 'text2' collection 看起来像这样:
$text2 = collect('cheese', 'bread', 'tomato');
我想从中提取的是 'text1' 和 'text2' 中的所有值。
所以在这种情况下,它应该 return:
'cheese', 'bread'
(因为这些值都在 'text1' 和 'text2' 中)
有没有简单的方法可以做到这一点?
非常感谢你帮助我。
此致
戴夫
你想要 intersect
method available on Collections:
$intersect = $text1->intersect($text2);
$intersect->all(); // [1 => 'cheese', 2 => 'bread']
在这种情况下,您需要 intersect 方法:
intersect 方法从原始集合中删除给定数组或集合中不存在的任何值。生成的集合将保留原始集合的键:
$text1Collection = collect('burger', 'cheese', 'bread', 'ham');
$text2Collection = collect('cheese', 'bread', 'tomato');
$resultCollection =$text1Collection->intersect($text2Collection);
亲爱的 Stack 溢出者,您好,
我正在尝试将一个 collection 与名称 'text1' 与另一个 collection 'text2'.
进行比较我想实现它将 'text1' 和 'text2' 都具有的所有值放入另一个 collection.
我已经尝试过使用 Diff 和 DiffKeys(参见 compare two collection arrays in laravel)。
但我无法完全理解如何使用这些函数将 2 collection 的值相互比较。在我看来,这两个函数(Diff 和 DiffKeys)需要一个密钥,我(还)没有专门使用它来提取我的 collections.
的部分内容我的 'text1' collection 看起来像这样:
$text1 = collect('burger', 'cheese', 'bread', 'ham');
我的 'text2' collection 看起来像这样:
$text2 = collect('cheese', 'bread', 'tomato');
我想从中提取的是 'text1' 和 'text2' 中的所有值。 所以在这种情况下,它应该 return:
'cheese', 'bread'
(因为这些值都在 'text1' 和 'text2' 中)
有没有简单的方法可以做到这一点?
非常感谢你帮助我。
此致
戴夫
你想要 intersect
method available on Collections:
$intersect = $text1->intersect($text2);
$intersect->all(); // [1 => 'cheese', 2 => 'bread']
在这种情况下,您需要 intersect 方法:
intersect 方法从原始集合中删除给定数组或集合中不存在的任何值。生成的集合将保留原始集合的键:
$text1Collection = collect('burger', 'cheese', 'bread', 'ham');
$text2Collection = collect('cheese', 'bread', 'tomato');
$resultCollection =$text1Collection->intersect($text2Collection);