如何检查数组是否包含多个字符串 Laravel
how to check if array contains multi strings Laravel
我有collection
Illuminate\Support\Collection {#1453
#items: array:4 [
0 => "three"
1 => "nine"
2 => "one"
3 => "two"
]
}
和这个字符串
'one', 'two', 'three'
我正在尝试验证这些所有字符串是否在数组中可用
$array->contains('one', 'two', 'three')
应该return正确
但每次我都弄错了
我做错了什么请解释谢谢
我使用 Collection:diff
in combination with Collection::isEmpty
作为可重复使用的 containsAll
宏。当提供的值包含未包含在集合中的元素时,检查 diff
的结果不会为空,因此 return 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
我有collection
Illuminate\Support\Collection {#1453
#items: array:4 [
0 => "three"
1 => "nine"
2 => "one"
3 => "two"
]
}
和这个字符串
'one', 'two', 'three'
我正在尝试验证这些所有字符串是否在数组中可用
$array->contains('one', 'two', 'three')
应该return正确
但每次我都弄错了
我做错了什么请解释谢谢
我使用 Collection:diff
in combination with Collection::isEmpty
作为可重复使用的 containsAll
宏。当提供的值包含未包含在集合中的元素时,检查 diff
的结果不会为空,因此 return 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