集合
简介
Illuminate\Support\Collection 类为处理数据数组提供了一个流畅、方便的包装器。例如,查看以下代码。我们将使用 collect 辅助函数从数组创建一个新的集合实例,对每个元素运行 strtoupper 函数,然后删除所有空元素:
$collection = collect(['Taylor', 'Abigail', null])->map(function (?string $name) {
return strtoupper($name);
})->reject(function (string $name) {
return empty($name);
});如您所见,Collection 类允许您链式调用其方法,对底层数组进行流畅的映射和缩减操作。通常,集合是不可变的,这意味着每个 Collection 方法都会返回一个全新的 Collection 实例。
创建集合
如上所述,collect 辅助函数为给定数组返回一个新的 Illuminate\Support\Collection 实例。因此,创建集合非常简单:
$collection = collect([1, 2, 3]);您也可以使用 make 和 fromJson 方法创建集合。
NOTE
Eloquent 查询的结果始终作为 Collection 实例返回。
扩展集合
集合是"可宏扩展的",这允许您在运行时向 Collection 类添加额外的方法。Illuminate\Support\Collection 类的 macro 方法接受一个闭包,该闭包将在您的宏被调用时执行。宏闭包可以通过 $this 访问集合的其他方法,就像它是集合类的真正方法一样。例如,以下代码向 Collection 类添加了一个 toUpper 方法:
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
Collection::macro('toUpper', function () {
return $this->map(function (string $value) {
return Str::upper($value);
});
});
$collection = collect(['first', 'second']);
$upper = $collection->toUpper();
// ['FIRST', 'SECOND']通常,您应该在服务提供者的 boot 方法中声明集合宏。
宏参数
如有必要,您可以定义接受额外参数的宏:
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Lang;
Collection::macro('toLocale', function (string $locale) {
return $this->map(function (string $value) use ($locale) {
return Lang::get($value, [], $locale);
});
});
$collection = collect(['first', 'second']);
$translated = $collection->toLocale('es');
// ['primero', 'segundo'];可用方法
在接下来的集合文档中,我们将讨论 Collection 类上可用的每个方法。请记住,所有这些方法都可以链式调用以流畅地操作底层数组。此外,几乎每个方法都返回一个新的 Collection 实例,允许您在必要时保留集合的原始副本:
afterallaverageavgbeforechunkchunkWhilecollapsecollapseWithKeyscollectcombineconcatcontainscontainsStrictcountcountBycrossJoindddiffdiffAssocdiffAssocUsingdiffKeysdoesntContaindoesntContainStrictdotdumpduplicatesduplicatesStricteacheachSpreadensureeveryexceptfilterfirstfirstOrFailfirstWhereflatMapflattenflipforgetforPagefromJsongetgroupByhashasAnyhasManyhasSoleimplodeintersectintersectUsingintersectAssocintersectAssocUsingintersectByKeysisEmptyisNotEmptyjoinkeyBykeyslastlazymacromakemapmapIntomapSpreadmapToGroupsmapWithKeysmaxmedianmergemergeRecursiveminmodemultiplynthonlypadpartitionpercentagepipepipeIntopipeThroughpluckpopprependpullpushputrandomrangereducereduceSpreadrejectreplacereplaceRecursivereversesearchselectshiftshuffleskipskipUntilskipWhilesliceslidingsolesomesortsortBysortByDescsortDescsortKeyssortKeysDescsortKeysUsingsplicesplitsplitInsumtaketakeUntiltakeWhiletaptimestoArraytoJsontoPrettyJsontransformundotunionuniqueuniqueStrictunlessunlessEmptyunlessNotEmptyunwrapvaluevalueswhenwhenEmptywhenNotEmptywherewhereStrictwhereBetweenwhereInwhereInStrictwhereInstanceOfwhereNotBetweenwhereNotInwhereNotInStrictwhereNotNullwhereNullwrapzip
方法列表
after()
after 方法返回给定项之后的项。如果未找到给定项或该项是最后一项,则返回 null:
$collection = collect([1, 2, 3, 4, 5]);
$collection->after(3);
// 4
$collection->after(5);
// null此方法使用"宽松"比较来搜索给定项,这意味着包含整数值的字符串将被视为等于相同值的整数。要使用"严格"比较,您可以为该方法提供 strict 参数:
collect([2, 4, 6, 8])->after('4', strict: true);
// null或者,您可以提供自己的闭包来搜索通过给定真值测试的第一项:
collect([2, 4, 6, 8])->after(function (int $item, int $key) {
return $item > 5;
});
// 8all()
all 方法返回集合表示的底层数组:
collect([1, 2, 3])->all();
// [1, 2, 3]average()
avg 方法的别名。
avg()
avg 方法返回给定键的平均值:
$average = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
])->avg('foo');
// 20
$average = collect([1, 1, 2, 4])->avg();
// 2before()
before 方法是 after 方法的相反。它返回给定项之前的项。如果未找到给定项或该项是第一项,则返回 null:
$collection = collect([1, 2, 3, 4, 5]);
$collection->before(3);
// 2
$collection->before(1);
// null
collect([2, 4, 6, 8])->before('4', strict: true);
// null
collect([2, 4, 6, 8])->before(function (int $item, int $key) {
return $item > 5;
});
// 4chunk()
chunk 方法将集合分解为给定大小的多个较小集合:
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->all();
// [[1, 2, 3, 4], [5, 6, 7]]此方法在视图中使用网格系统(如 Bootstrap)时特别有用。例如,假设您有一个要在网格中显示的 Eloquent 模型集合:
@foreach ($products->chunk(3) as $chunk)
<div class="row">
@foreach ($chunk as $product)
<div class="col-xs-4">{{ $product->name }}</div>
@endforeach
</div>
@endforeachchunkWhile()
chunkWhile 方法根据给定回调的评估将集合分解为多个较小的集合。传递给闭包的 $chunk 变量可用于检查前一个元素:
$collection = collect(str_split('AABBCCCD'));
$chunks = $collection->chunkWhile(function (string $value, int $key, Collection $chunk) {
return $value === $chunk->last();
});
$chunks->all();
// [['A', 'A'], ['B', 'B'], ['C', 'C', 'C'], ['D']]collapse()
collapse 方法将数组或集合的集合折叠为单个扁平集合:
$collection = collect([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]);
$collapsed = $collection->collapse();
$collapsed->all();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]collapseWithKeys()
collapseWithKeys 方法将数组或集合的集合扁平化为单个集合,保持原始键不变。如果集合已经是扁平的,它将返回一个空集合:
$collection = collect([
['first' => collect([1, 2, 3])],
['second' => [4, 5, 6]],
['third' => collect([7, 8, 9])]
]);
$collapsed = $collection->collapseWithKeys();
$collapsed->all();
// [
// 'first' => [1, 2, 3],
// 'second' => [4, 5, 6],
// 'third' => [7, 8, 9],
// ]collect()
collect 方法返回一个包含集合中当前项的新 Collection 实例:
$collectionA = collect([1, 2, 3]);
$collectionB = $collectionA->collect();
$collectionB->all();
// [1, 2, 3]collect 方法主要用于将延迟集合转换为标准 Collection 实例:
$lazyCollection = LazyCollection::make(function () {
yield 1;
yield 2;
yield 3;
});
$collection = $lazyCollection->collect();
$collection::class;
// 'Illuminate\Support\Collection'
$collection->all();
// [1, 2, 3]NOTE
当您拥有 Enumerable 实例并需要非延迟集合实例时,collect 方法特别有用。由于 collect() 是 Enumerable 契约的一部分,您可以安全地使用它来获取 Collection 实例。
combine()
combine 方法将集合的值作为键与另一个数组或集合的值组合:
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]concat()
concat 方法将给定数组或集合的值附加到另一个集合的末尾:
$collection = collect(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
$concatenated->all();
// ['John Doe', 'Jane Doe', 'Johnny Doe']concat 方法对附加到原始集合的项重新进行数字索引。要在关联集合中保持键,请参阅 merge 方法。
contains()
contains 方法确定集合是否包含给定项。您可以将闭包传递给 contains 方法,以确定集合中是否存在匹配给定真值测试的元素:
$collection = collect([1, 2, 3, 4, 5]);
$collection->contains(function (int $value, int $key) {
return $value > 5;
});
// false或者,您可以将字符串传递给 contains 方法,以确定集合是否包含给定项值:
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->contains('Desk');
// true
$collection->contains('New York');
// false您还可以将键/值对传递给 contains 方法,这将确定集合中是否存在给定的对:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->contains('product', 'Bookcase');
// falsecontains 方法在检查项值时使用"宽松"比较,这意味着具有整数值的字符串将被视为等于相同值的整数。使用 containsStrict 方法使用"严格"比较进行过滤。
有关 contains 的反向操作,请参阅 doesntContain 方法。
containsStrict()
此方法与 contains 方法具有相同的签名;但是,所有值都使用"严格"比较进行比较。
NOTE
使用 Eloquent 集合时,此方法的行为会有所修改。
count()
count 方法返回集合中的项总数:
$collection = collect([1, 2, 3, 4]);
$collection->count();
// 4countBy()
countBy 方法计算集合中值的出现次数。默认情况下,该方法计算每个元素的出现次数,允许您计算集合中某些"类型"的元素:
$collection = collect([1, 2, 2, 2, 3]);
$counted = $collection->countBy();
$counted->all();
// [1 => 1, 2 => 3, 3 => 1]您可以将闭包传递给 countBy 方法,以按自定义值计算所有项:
$collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']);
$counted = $collection->countBy(function (string $email) {
return substr(strrchr($email, '@'), 1);
});
$counted->all();
// ['gmail.com' => 2, 'yahoo.com' => 1]crossJoin()
crossJoin 方法在给定数组或集合之间交叉连接集合的值,返回包含所有可能排列的笛卡尔积:
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b']);
$matrix->all();
/*
[
[1, 'a'],
[1, 'b'],
[2, 'a'],
[2, 'b'],
]
*/
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);
$matrix->all();
/*
[
[1, 'a', 'I'],
[1, 'a', 'II'],
[1, 'b', 'I'],
[1, 'b', 'II'],
[2, 'a', 'I'],
[2, 'a', 'II'],
[2, 'b', 'I'],
[2, 'b', 'II'],
]
*/dd()
dd 方法转储集合的项并结束脚本的执行:
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
/*
array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
*/如果您不想停止执行脚本,请改用 dump 方法。
diff()
diff 方法根据值将集合与另一个集合或普通 PHP array 进行比较。此方法将返回原始集合中不存在于给定集合中的值:
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]NOTE
使用 Eloquent 集合时,此方法的行为会有所修改。
diffAssoc()
diffAssoc 方法根据键和值将集合与另一个集合或普通 PHP array 进行比较。此方法将返回原始集合中不存在于给定集合中的键/值对:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6,
]);
$diff = $collection->diffAssoc([
'color' => 'yellow',
'type' => 'fruit',
'remain' => 3,
'used' => 6,
]);
$diff->all();
// ['color' => 'orange', 'remain' => 6]diffAssocUsing()
与 diffAssoc 不同,diffAssocUsing 接受用户提供的回调函数用于索引比较:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6,
]);
$diff = $collection->diffAssocUsing([
'Color' => 'yellow',
'Type' => 'fruit',
'Remain' => 3,
], 'strnatcasecmp');
$diff->all();
// ['color' => 'orange', 'remain' => 6]diffKeys()
diffKeys 方法根据键将集合与另一个集合或普通 PHP array 进行比较。此方法将返回原始集合中不存在于给定集合中的键/值对:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6,
]);
$diff = $collection->diffKeys([
'color' => 'yellow',
'type' => 'pear',
]);
$diff->all();
// ['remain' => 6]doesntContain()
doesntContain 方法确定集合是否不包含给定项。您可以将闭包传递给 doesntContain 方法,以确定集合中是否不存在匹配给定真值测试的元素:
$collection = collect([1, 2, 3, 4, 5]);
$collection->doesntContain(function (int $value, int $key) {
return $value > 5;
});
// true或者,您可以将字符串传递给 doesntContain 方法,以确定集合是否不包含给定项值:
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->doesntContain('Desk');
// false
$collection->doesntContain('New York');
// true您还可以将键/值对传递给 doesntContain 方法,这将确定集合中是否不存在给定的对:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->doesntContain('product', 'Bookcase');
// truedoesntContain 方法在检查项值时使用"宽松"比较,这意味着具有整数值的字符串将被视为等于相同值的整数。
dot()
dot 方法将多维集合扁平化为单级集合,使用"点"符号表示深度:
$collection = collect(['name' => 'Taylor', 'languages' => ['php', 'javascript']]);
$flattened = $collection->dot();
$flattened->all();
// ['name' => 'Taylor', 'languages.0' => 'php', 'languages.1' => 'javascript'];dump()
dump 方法转储集合的项而不结束脚本的执行:
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dump();
/*
array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
*/如果您想在转储集合后停止执行脚本,请改用 dd 方法。
duplicates()
duplicates 方法返回集合中的重复值:
$collection = collect(['a', 'b', 'a', 'c', 'b']);
$duplicates = $collection->duplicates();
$duplicates->all();
// [2 => 'a', 4 => 'b']如果集合包含数组或对象,您可以传递要检查重复项的属性键:
$collection = collect([
['email' => 'abigail@example.com', 'position' => 'Developer'],
['email' => 'james@example.com', 'position' => 'Designer'],
['email' => 'victoria@example.com', 'position' => 'Developer'],
]);
$duplicates = $collection->duplicates('position');
$duplicates->all();
// [2 => 'Developer']duplicatesStrict()
此方法与 duplicates 方法具有相同的签名;但是,所有值都使用"严格"比较进行比较。
each()
each 方法遍历集合中的项并将每个项传递给闭包:
$collection = collect([1, 2, 3, 4]);
$collection->each(function (int $item, int $key) {
// ...
});如果您想停止遍历项,可以从闭包返回 false:
$collection->each(function (int $item, int $key) {
if ($item > 2) {
return false;
}
});eachSpread()
eachSpread 方法遍历集合的项,将每个嵌套项值传递给给定的闭包:
$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);
$collection->eachSpread(function (string $name, int $age) {
// ...
});您可以通过从闭包返回 false 来停止遍历项:
$collection->eachSpread(function (string $name, int $age) {
return false;
});ensure()
ensure 方法验证集合的所有元素是否属于给定类型或类型列表。如果任何元素不是给定类型之一,将抛出 UnexpectedValueException:
return $collection->ensure(User::class);
return $collection->ensure([User::class, Customer::class]);也可以指定原始类型,如 int、float、string、bool、array、null 和 object:
return $collection->ensure('int');WARNING
ensure 方法不能保证后续添加到集合中的元素将是给定类型。
every()
every 方法可用于验证集合中的所有元素是否通过给定的真值测试:
collect([1, 2, 3, 4])->every(function (int $value, int $key) {
return $value > 2;
});
// false如果集合为空,every 方法将返回 true:
collect([])->every(function (int $value, int $key) {
return $value > 2;
});
// trueexcept()
except 方法返回集合中除指定键之外的所有项:
$collection = collect([
'product_id' => 1,
'name' => 'Desk',
'price' => 100,
'discount' => false
]);
$filtered = $collection->except(['price', 'discount']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']有关 except 的反向操作,请参阅 only 方法。
NOTE
使用 Eloquent 集合时,此方法的行为会有所修改。
filter()
filter 方法使用给定的回调过滤集合,只保留通过给定真值测试的项:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function (int $value, int $key) {
return $value > 2;
});
$filtered->all();
// [3, 4]如果没有提供回调,集合中所有等于 false 的项将被删除:
$collection = collect([1, 2, 3, null, false, '', 0, []]);
$collection->filter()->all();
// [1, 2, 3]有关 filter 的反向操作,请参阅 reject 方法。
first()
first 方法返回集合中通过给定真值测试的第一个元素:
collect([1, 2, 3, 4])->first(function (int $value, int $key) {
return $value > 2;
});
// 3您也可以不带参数调用 first 方法来获取集合中的第一个元素。如果集合为空,则返回 null:
collect([1, 2, 3, 4])->first();
// 1firstOrFail()
firstOrFail 方法与 first 方法相同;但是,如果没有找到项,将抛出 Illuminate\Support\ItemNotFoundException 异常:
collect([1, 2, 3, 4])->firstOrFail(function (int $value, int $key) {
return $value > 5;
});
// 抛出 ItemNotFoundException您也可以不带参数调用 firstOrFail 方法来获取集合中的第一个元素。如果集合为空,将抛出 Illuminate\Support\ItemNotFoundException 异常:
collect([])->firstOrFail();
// 抛出 ItemNotFoundExceptionfirstWhere()
firstWhere 方法返回集合中具有给定键/值对的第一个元素:
$collection = collect([
['name' => 'Regena', 'age' => null],
['name' => 'Linda', 'age' => 14],
['name' => 'Diego', 'age' => 23],
['name' => 'Linda', 'age' => 84],
]);
$collection->firstWhere('name', 'Linda');
// ['name' => 'Linda', 'age' => 14]您也可以使用比较运算符调用 firstWhere 方法:
$collection->firstWhere('age', '>=', 18);
// ['name' => 'Diego', 'age' => 23]与 where 方法类似,您可以将一个参数传递给 firstWhere 方法。在这种情况下,firstWhere 方法将返回给定键值为"真"的第一个项:
$collection->firstWhere('age');
// ['name' => 'Linda', 'age' => 14]flatMap()
flatMap 方法遍历集合并将每个值传递给给定的闭包。闭包可以修改项并返回它,从而形成一个新的修改项集合。然后,集合被扁平化一级:
$collection = collect([
['name' => 'Sally'],
['school' => 'Arkansas'],
['age' => 28]
]);
$flattened = $collection->flatMap(function (array $values) {
return array_map('strtoupper', $values);
});
$flattened->all();
// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];flatten()
flatten 方法将多维集合扁平化为单维集合:
$collection = collect([
'name' => 'Taylor',
'languages' => [
'php', 'javascript'
]
]);
$flattened = $collection->flatten();
$flattened->all();
// ['Taylor', 'php', 'javascript'];如有必要,您可以向 flatten 方法传递一个"深度"参数:
$collection = collect([
'Apple' => [
[
'name' => 'iPhone 6S',
'brand' => 'Apple'
],
],
'Samsung' => [
[
'name' => 'Galaxy S7',
'brand' => 'Samsung'
],
],
]);
$products = $collection->flatten(1);
$products->values()->all();
/*
[
['name' => 'iPhone 6S', 'brand' => 'Apple'],
['name' => 'Galaxy S7', 'brand' => 'Samsung'],
]
*/flip()
flip 方法将集合的键与其对应的值交换:
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
$flipped = $collection->flip();
$flipped->all();
// ['Taylor' => 'name', 'Laravel' => 'framework']forget()
forget 方法通过键从集合中删除项:
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
$collection->forget('name');
$collection->all();
// ['framework' => 'Laravel']WARNING
与大多数其他集合方法不同,forget 不返回新的修改后的集合;它修改调用它的集合。
forPage()
forPage 方法返回一个包含给定页码上项的新集合。该方法接受页码作为第一个参数,每页显示的项数作为第二个参数:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);
$chunk->all();
// [4, 5, 6]fromJson()
fromJson 方法从 JSON 字符串创建一个新集合:
$collection = Collection::fromJson('[1, 2, 3, 4]');
$collection->all();
// [1, 2, 3, 4]get()
get 方法返回给定键的项。如果键不存在,则返回 null:
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
$value = $collection->get('name');
// Taylor您可以选择传递默认值作为第二个参数:
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
$value = $collection->get('age', 18);
// 18您甚至可以将闭包作为默认值传递。如果指定的键不存在,将返回闭包的结果:
$collection->get('email', function () {
return 'taylor@example.com';
});
// taylor@example.comgroupBy()
groupBy 方法按给定键对集合的项进行分组:
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->all();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/您可以传递回调而不是字符串键。回调应返回您希望作为键分组的值:
$grouped = $collection->groupBy(function (array $item, int $key) {
return substr($item['account_id'], -3);
});
$grouped->all();
/*
[
'x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/多个分组标准可以作为数组传递。每个数组元素将应用于多维数组中的对应级别:
$data = new Collection([
10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
]);
$result = $data->groupBy(['skill', function (array $item) {
return $item['roles'];
}], preserveKeys: true);
/*
[
1 => [
'Role_1' => [
10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
],
'Role_2' => [
20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
],
'Role_3' => [
10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
],
],
2 => [
'Role_1' => [
30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
],
'Role_2' => [
40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
],
],
];
*/has()
has 方法确定集合中是否存在给定键:
$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
$collection->has('product');
// true
$collection->has(['product', 'amount']);
// true
$collection->has(['product', 'price']);
// falsehasAny()
hasAny 方法确定集合中是否存在任何给定键:
$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
$collection->hasAny(['product', 'price']);
// true
$collection->hasAny(['name', 'price']);
// falsehasMany()
hasMany 方法确定集合中是否存在所有给定键:
$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
$collection->hasMany(['product', 'amount']);
// true
$collection->hasMany(['product', 'price']);
// falsehasSole()
hasSole 方法确定集合中是否只存在一个给定键:
$collection = collect(['product' => 'Desk']);
$collection->hasSole('product');
// true
$collection = collect(['product' => 'Desk', 'name' => 'Chair']);
$collection->hasSole('product');
// falseimplode()
implode 方法连接集合中的项。其参数取决于集合中项的类型。如果集合包含数组或对象,您应该传递要连接的属性键,以及您希望放置在值之间的"粘合"字符串:
$collection = collect([
['account_id' => 1, 'product' => 'Chair'],
['account_id' => 2, 'product' => 'Desk'],
]);
$collection->implode('product', ', ');
// Chair, Desk如果集合包含简单字符串或数值,您应该将"粘合"字符串作为方法的唯一参数传递:
collect([1, 2, 3, 4, 5])->implode('-');
// '1-2-3-4-5'如有必要,您可以传递一个闭包给 implode 方法,该方法应返回您希望连接的字符串值:
$collection->implode(function (array $item, int $key) {
return strtoupper($item['product']);
}, ', ');
// CHAIR, DESKintersect()
intersect 方法从原始集合中删除给定数组或集合中不存在的任何值。生成的集合将保留原始集合的键:
$collection = collect(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']NOTE
使用 Eloquent 集合时,此方法的行为会有所修改。
intersectUsing()
intersectUsing 方法使用自定义回调比较值,从原始集合中删除给定数组或集合中不存在的任何值。生成的集合将保留原始集合的键:
$collection = collect(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersectUsing(['desk', 'chair', 'bookcase'], function (string $a, string $b) {
return strcasecmp($a, $b);
});
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']intersectAssoc()
intersectAssoc 方法将原始集合与另一个集合或数组进行比较,返回所有给定集合中都存在的键/值对:
$collection = collect([
'color' => 'red',
'size' => 'M',
'material' => 'cotton'
]);
$intersect = $collection->intersectAssoc([
'color' => 'blue',
'size' => 'M',
'material' => 'polyester'
]);
$intersect->all();
// ['size' => 'M']intersectAssocUsing()
intersectAssocUsing 方法将原始集合与另一个集合或数组进行比较,返回两者中都存在的键/值对,使用自定义比较回调来确定键和值的相等性:
$collection = collect([
'color' => 'red',
'Size' => 'M',
'material' => 'cotton',
]);
$intersect = $collection->intersectAssocUsing([
'color' => 'blue',
'size' => 'M',
'material' => 'polyester',
], function (string $a, string $b) {
return strcasecmp($a, $b);
});
$intersect->all();
// ['Size' => 'M']intersectByKeys()
intersectByKeys 方法从原始集合中删除给定数组或集合中不存在的任何键及其对应的值:
$collection = collect([
'serial' => 'UX301', 'type' => 'screen', 'year' => 2009,
]);
$intersect = $collection->intersectByKeys([
'reference' => 'UX404', 'type' => 'tab', 'year' => 2011,
]);
$intersect->all();
// ['type' => 'screen', 'year' => 2009]isEmpty()
如果集合为空,isEmpty 方法返回 true;否则返回 false:
collect([])->isEmpty();
// trueisNotEmpty()
如果集合不为空,isNotEmpty 方法返回 true;否则返回 false:
collect([])->isNotEmpty();
// falsejoin()
join 方法使用字符串连接集合的值。使用此方法的第二个参数,您还可以指定如何将最后一个元素附加到字符串:
collect(['a', 'b', 'c'])->join(', '); // 'a, b, c'
collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'
collect(['a', 'b'])->join(', ', ' and '); // 'a and b'
collect(['a'])->join(', ', ' and '); // 'a'
collect([])->join(', ', ' and '); // ''keyBy()
keyBy 方法按给定键对集合进行键控。如果多个项具有相同的键,只有最后一个会出现在新集合中:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keyed = $collection->keyBy('product_id');
$keyed->all();
/*
[
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/您也可以向该方法传递回调。回调应返回用于键控集合的值:
$keyed = $collection->keyBy(function (array $item, int $key) {
return strtoupper($item['product_id']);
});
$keyed->all();
/*
[
'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/keys()
keys 方法返回集合的所有键:
$collection = collect([
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keys = $collection->keys();
$keys->all();
// ['prod-100', 'prod-200']last()
last 方法返回集合中通过给定真值测试的最后一个元素:
collect([1, 2, 3, 4])->last(function (int $value, int $key) {
return $value < 3;
});
// 2您也可以不带参数调用 last 方法来获取集合中的最后一个元素。如果集合为空,则返回 null:
collect([1, 2, 3, 4])->last();
// 4lazy()
lazy 方法从底层项数组返回一个新的 LazyCollection 实例:
$lazyCollection = collect([1, 2, 3, 4])->lazy();
$lazyCollection::class;
// Illuminate\Support\LazyCollection
$lazyCollection->all();
// [1, 2, 3, 4]当您需要对包含许多项的巨大 Collection 执行转换时,这特别有用:
$count = $hugeCollection
->lazy()
->where('country', 'FR')
->where('balance', '>', '100')
->count();通过将集合转换为 LazyCollection,我们避免分配大量额外内存。虽然原始集合仍然将其值保留在内存中,但后续的过滤器不会。因此,在过滤集合结果时几乎不会分配额外的内存。
macro()
静态 macro 方法允许您在运行时向 Collection 类添加方法。有关更多信息,请参阅有关扩展集合的文档。
make()
静态 make 方法创建一个新的集合实例。请参阅创建集合部分。
use Illuminate\Support\Collection;
$collection = Collection::make([1, 2, 3]);map()
map 方法遍历集合并将每个值传递给给定的回调。回调可以自由修改项并返回它,从而形成一个新的修改项集合:
$collection = collect([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function (int $item, int $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]WARNING
与大多数其他集合方法一样,map 返回一个新的集合实例;它不会修改调用它的集合。如果您想转换原始集合,请使用 transform 方法。
mapInto()
mapInto() 方法遍历集合,通过将值传递给构造函数来创建给定类的新实例:
class Currency
{
/**
* 创建一个新的货币实例。
*/
function __construct(
public string $code,
) {}
}
$collection = collect(['USD', 'EUR', 'GBP']);
$currencies = $collection->mapInto(Currency::class);
$currencies->all();
// [Currency('USD'), Currency('EUR'), Currency('GBP')]mapSpread()
mapSpread 方法遍历集合的项,将每个嵌套项值传递给给定的闭包。闭包可以自由修改项并返回它,从而形成一个新的修改项集合:
$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunks = $collection->chunk(2);
$sequence = $chunks->mapSpread(function (int $even, int $odd) {
return $even + $odd;
});
$sequence->all();
// [1, 5, 9, 13, 17]mapToGroups()
mapToGroups 方法按给定闭包对集合的项进行分组。闭包应返回包含单个键/值对的关联数组,从而形成一个新的分组值集合:
$collection = collect([
[
'name' => 'John Doe',
'department' => 'Sales',
],
[
'name' => 'Jane Doe',
'department' => 'Sales',
],
[
'name' => 'Johnny Doe',
'department' => 'Marketing',
]
]);
$grouped = $collection->mapToGroups(function (array $item, int $key) {
return [$item['department'] => $item['name']];
});
$grouped->all();
/*
[
'Sales' => ['John Doe', 'Jane Doe'],
'Marketing' => ['Johnny Doe'],
]
*/
$grouped->get('Sales')->all();
// ['John Doe', 'Jane Doe']mapWithKeys()
mapWithKeys 方法遍历集合并将每个值传递给给定的回调。回调应返回包含单个键/值对的关联数组:
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john@example.com',
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane@example.com',
]
]);
$keyed = $collection->mapWithKeys(function (array $item, int $key) {
return [$item['email'] => $item['name']];
});
$keyed->all();
/*
[
'john@example.com' => 'John',
'jane@example.com' => 'Jane',
]
*/max()
max 方法返回给定键的最大值:
$max = collect([
['foo' => 10],
['foo' => 20]
])->max('foo');
// 20
$max = collect([1, 2, 3, 4, 5])->max();
// 5median()
median 方法返回给定键的中位数:
$median = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
])->median('foo');
// 15
$median = collect([1, 1, 2, 4])->median();
// 1.5merge()
merge 方法将给定数组或集合与原始集合合并。如果给定项中的字符串键与原始集合中的字符串键匹配,则给定项的值将覆盖原始集合中的值:
$collection = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'price' => 200, 'discount' => false]如果给定项的键是数字,则值将附加到集合的末尾:
$collection = collect(['Desk', 'Chair']);
$merged = $collection->merge(['Bookcase', 'Door']);
$merged->all();
// ['Desk', 'Chair', 'Bookcase', 'Door']mergeRecursive()
mergeRecursive 方法将给定数组或集合递归地与原始集合合并。如果给定项中的字符串键与原始集合中的字符串键匹配,则这些键的值将合并到一个数组中,并且这是递归完成的:
$collection = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->mergeRecursive([
'product_id' => 2,
'price' => 200,
'discount' => false
]);
$merged->all();
// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]min()
min 方法返回给定键的最小值:
$min = collect([
['foo' => 10],
['foo' => 20]
])->min('foo');
// 10
$min = collect([1, 2, 3, 4, 5])->min();
// 1mode()
mode 方法返回给定键的众数:
$mode = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
])->mode('foo');
// [10]
$mode = collect([1, 1, 2, 4])->mode();
// [1]
$mode = collect([1, 1, 2, 2])->mode();
// [1, 2]multiply()
multiply 方法创建集合中所有项的指定数量的副本:
$users = collect([
['name' => 'User #1', 'email' => 'user1@example.com'],
['name' => 'User #2', 'email' => 'user2@example.com'],
])->multiply(3);
/*
[
['name' => 'User #1', 'email' => 'user1@example.com'],
['name' => 'User #2', 'email' => 'user2@example.com'],
['name' => 'User #1', 'email' => 'user1@example.com'],
['name' => 'User #2', 'email' => 'user2@example.com'],
['name' => 'User #1', 'email' => 'user1@example.com'],
['name' => 'User #2', 'email' => 'user2@example.com'],
]
*/nth()
nth 方法创建一个由每隔 n 个元素组成的新集合:
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->nth(4);
// ['a', 'e']您可以选择传递起始偏移量作为第二个参数:
$collection->nth(4, 1);
// ['b', 'f']only()
only 方法返回集合中具有指定键的项:
$collection = collect([
'product_id' => 1,
'name' => 'Desk',
'price' => 100,
'discount' => false
]);
$filtered = $collection->only(['product_id', 'name']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']有关 only 的反向操作,请参阅 except 方法。
NOTE
使用 Eloquent 集合时,此方法的行为会有所修改。
pad()
pad 方法将使用给定值填充数组,直到数组达到指定大小。此方法的行为类似于 PHP 的 array_pad 函数。
要向左填充,您应该指定一个负大小。如果给定大小的绝对值小于或等于数组的长度,则不会发生填充:
$collection = collect(['A', 'B', 'C']);
$filtered = $collection->pad(5, 0);
$filtered->all();
// ['A', 'B', 'C', 0, 0]
$filtered = $collection->pad(-5, 0);
$filtered->all();
// [0, 0, 'A', 'B', 'C']partition()
partition 方法可以与 PHP 数组解构结合使用,将通过给定真值测试的元素与未通过的元素分开:
$collection = collect([1, 2, 3, 4, 5, 6]);
[$underThree, $equalOrAboveThree] = $collection->partition(function (int $i) {
return $i < 3;
});
$underThree->all();
// [1, 2]
$equalOrAboveThree->all();
// [3, 4, 5, 6]NOTE
与 Eloquent 集合交互时,此方法的行为会有所修改。
percentage()
percentage 方法可用于快速确定集合中通过给定真值测试的项的百分比:
$collection = collect([1, 1, 2, 2, 2, 3]);
$percentage = $collection->percentage(fn (int $value) => $value === 1);
// 33.33默认情况下,百分比将四舍五入到两位小数。但是,您可以通过向方法提供第二个参数来自定义此行为:
$percentage = $collection->percentage(fn (int $value) => $value === 1, precision: 3);
// 33.333pipe()
pipe 方法将集合传递给给定的闭包并返回执行闭包的结果:
$collection = collect([1, 2, 3]);
$piped = $collection->pipe(function (Collection $collection) {
return $collection->sum();
});
// 6pipeInto()
pipeInto 方法创建给定类的新实例并将集合传递给构造函数:
class ResourceCollection
{
/**
* 创建一个新的 ResourceCollection 实例。
*/
public function __construct(
public Collection $collection,
) {}
}
$collection = collect([1, 2, 3]);
$resource = $collection->pipeInto(ResourceCollection::class);
$resource->collection->all();
// [1, 2, 3]pipeThrough()
pipeThrough 方法将集合传递给给定的闭包数组并返回执行闭包的结果:
use Illuminate\Support\Collection;
$collection = collect([1, 2, 3]);
$result = $collection->pipeThrough([
function (Collection $collection) {
return $collection->merge([4, 5]);
},
function (Collection $collection) {
return $collection->sum();
},
]);
// 15pluck()
pluck 方法检索给定键的所有值:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']您还可以指定希望结果集合如何键控:
$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']pluck 方法还支持使用"点"符号检索嵌套值:
$collection = collect([
[
'name' => 'Laracon',
'speakers' => [
'first_day' => ['Rosa', 'Judith'],
],
],
[
'name' => 'VueConf',
'speakers' => [
'first_day' => ['Abigail', 'Joey'],
],
],
]);
$plucked = $collection->pluck('speakers.first_day');
$plucked->all();
// [['Rosa', 'Judith'], ['Abigail', 'Joey']]如果存在重复键,最后一个匹配元素将被插入到提取的集合中:
$collection = collect([
['brand' => 'Tesla', 'color' => 'red'],
['brand' => 'Pagani', 'color' => 'white'],
['brand' => 'Tesla', 'color' => 'black'],
['brand' => 'Pagani', 'color' => 'orange'],
]);
$plucked = $collection->pluck('color', 'brand');
$plucked->all();
// ['Tesla' => 'black', 'Pagani' => 'orange']pop()
pop 方法删除并返回集合中的最后一项。如果集合为空,将返回 null:
$collection = collect([1, 2, 3, 4, 5]);
$collection->pop();
// 5
$collection->all();
// [1, 2, 3, 4]您可以将整数传递给 pop 方法,以从集合末尾删除并返回多个项:
$collection = collect([1, 2, 3, 4, 5]);
$collection->pop(3);
// collect([5, 4, 3])
$collection->all();
// [1, 2]prepend()
prepend 方法将项添加到集合的开头:
$collection = collect([1, 2, 3, 4, 5]);
$collection->prepend(0);
$collection->all();
// [0, 1, 2, 3, 4, 5]您还可以传递第二个参数来指定前置项的键:
$collection = collect(['one' => 1, 'two' => 2]);
$collection->prepend(0, 'zero');
$collection->all();
// ['zero' => 0, 'one' => 1, 'two' => 2]pull()
pull 方法通过键从集合中删除并返回项:
$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);
$collection->pull('name');
// 'Desk'
$collection->all();
// ['product_id' => 'prod-100']push()
push 方法将项添加到集合的末尾:
$collection = collect([1, 2, 3, 4]);
$collection->push(5);
$collection->all();
// [1, 2, 3, 4, 5]put()
put 方法在集合中设置给定的键和值:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->put('price', 100);
$collection->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]random()
random 方法从集合中返回一个随机项:
$collection = collect([1, 2, 3, 4, 5]);
$collection->random();
// 4 - (随机检索)您可以传递一个整数给 random 方法,以指定要随机检索的项数。当明确传递项数时,将返回项的集合:
$random = $collection->random(3);
$random->all();
// [2, 4, 5] - (随机检索)如果集合中的项少于请求的数量,该方法将抛出 InvalidArgumentException。
range()
range 方法返回一个包含指定范围整数的集合:
$collection = Collection::range(1, 10);
$collection->all();
// [1, 2, 3, 4, 5, 6, 7, 8,