【问题标题】:how to check if array contains multi strings Laravel如何检查数组是否包含多个字符串 Laravel
【发布时间】:2021-04-06 22:24:44
【问题描述】:
我有收藏
Illuminate\Support\Collection {#1453
#items: array:4 [
0 => "three"
1 => "nine"
2 => "one"
3 => "two"
]
}
还有这个字符串
'one', 'two', 'three'
我正在尝试验证这些字符串是否在数组中可用
$array->contains('one', 'two', 'three')
它应该返回 true
但每次我都弄错了
我做错了什么,请解释一下,谢谢
【问题讨论】:
标签:
laravel
laravel-5
laravel-6
laravel-7
laravel-8
【解决方案1】:
我将Collection:diff 与Collection::isEmpty 结合使用以形成可重复使用的containsAll 宏。当提供的值包含集合中未包含的元素以检查 diff 的结果时,不会为空,因此返回 false。
use Illuminate\Support\Collection;
Collection::macro('containsAll', function (...$values) {
return collect($values)->diff($this)->isEmpty();
});
$collection = collect(['three', 'nine', 'one', 'two']);
$collection->containsAll('one', 'two', 'three'); // true
$collection->containsAll('one', 'five', 'three'); // false