Collections
介绍
该类Illuminate\Support\Collection
提供了一个流畅、便捷的包装器,用于处理数据数组。例如,查看以下代码。我们将使用该collect
辅助函数从数组创建一个新的集合实例,strtoupper
对每个元素运行该函数,然后删除所有空元素:
1$collection = collect(['Taylor', 'Abigail', null])->map(function (?string $name) {2 return strtoupper($name);3})->reject(function (string $name) {4 return empty($name);5});
如您所见,该类Collection
允许您链接其方法以执行底层数组的流畅映射和缩减。通常,集合是不可变的,这意味着每个Collection
方法都返回一个全新的Collection
实例。
创建集合
如上所述,该collect
辅助函数返回给定数组的新Illuminate\Support\Collection
实例。因此,创建集合非常简单:
1$collection = collect([1, 2, 3]);
您还可以使用make和fromJson方法创建集合。
Eloquent查询
的结果总是以Collection
实例的形式返回。
扩展集合
Collection
集合是“可宏的”,这意味着你可以在运行时向类添加额外的方法。Illuminate\Support\Collection
类的macro
方法接受一个闭包,当你的宏被调用时,闭包会被执行。宏闭包可以通过 访问集合的其他方法$this
,就像它是集合类的真实方法一样。例如,以下代码toUpper
向类添加了一个方法Collection
:
1use Illuminate\Support\Collection; 2use Illuminate\Support\Str; 3 4Collection::macro('toUpper', function () { 5 return $this->map(function (string $value) { 6 return Str::upper($value); 7 }); 8}); 9 10$collection = collect(['first', 'second']);11 12$upper = $collection->toUpper();13 14// ['FIRST', 'SECOND']
通常,您应该在服务提供商boot
的方法中声明集合宏。
宏参数
如果需要的话,你可以定义接受附加参数的宏:
1use Illuminate\Support\Collection; 2use Illuminate\Support\Facades\Lang; 3 4Collection::macro('toLocale', function (string $locale) { 5 return $this->map(function (string $value) use ($locale) { 6 return Lang::get($value, [], $locale); 7 }); 8}); 9 10$collection = collect(['first', 'second']);11 12$translated = $collection->toLocale('es');
可用方法
在其余大部分集合文档中,我们将讨论该类中可用的每个方法Collection
。请记住,所有这些方法都可以链接起来,以便流畅地操作底层数组。此外,几乎每个方法都会返回一个新Collection
实例,以便您在必要时保留集合的原始副本:
after all average avg before chunk chunkWhile collapse collapseWithKeys collect combine concat contains containsOneItem containsStrict count countBy crossJoin dd diff diffAssoc diffAssocUsing diffKeys doesntContain dot dump duplicates duplicatesStrict each eachSpread ensure every except filter first firstOrFail firstWhere flatMap flatten flip forget forPage fromJson get groupBy has hasAny implode intersect intersectUsing intersectAssoc intersectAssocUsing intersectByKeys isEmpty isNotEmpty join keyBy keys last lazy macro make map mapInto mapSpread mapToGroups mapWithKeys max median merge mergeRecursive min mode multiply nth only pad partition percentage pipe pipeInto pipeThrough pluck pop prepend pull push put random range reduce reduceSpread reject replace replaceRecursive reverse search select shift shuffle skip skipUntil skipWhile slice sliding sole some sort sortBy sortByDesc sortDesc sortKeys sortKeysDesc sortKeysUsing splice split splitIn sum take takeUntil takeWhile tap times toArray toJson transform undot union unique uniqueStrict unless unlessEmpty unlessNotEmpty unwrap value values when whenEmpty whenNotEmpty where whereStrict whereBetween whereIn whereInStrict whereInstanceOf whereNotBetween whereNotIn whereNotInStrict whereNotNull whereNull wrap zip
方法列表
after()
该after
方法返回给定项之后的项。null
如果未找到给定项或者是最后一项,则返回:
1$collection = collect([1, 2, 3, 4, 5]);2 3$collection->after(3);4 5// 46 7$collection->after(5);8 9// null
此方法使用“松散”比较来搜索给定项,这意味着包含整数值的字符串将被视为等于相同值的整数。要使用“严格”比较,您可以strict
向该方法提供以下参数:
1collect([2, 4, 6, 8])->after('4', strict: true);2 3// null
或者,您可以提供自己的闭包来搜索通过给定真实性测试的第一个项目:
1collect([2, 4, 6, 8])->after(function (int $item, int $key) {2 return $item > 5;3});4 5// 8
all()
该all
方法返回集合所表示的底层数组:
1collect([1, 2, 3])->all();2 3// [1, 2, 3]
average()
avg方法的别名。
avg()
该avg
方法返回给定键的平均值:
1$average = collect([ 2 ['foo' => 10], 3 ['foo' => 10], 4 ['foo' => 20], 5 ['foo' => 40] 6])->avg('foo'); 7 8// 20 9 10$average = collect([1, 1, 2, 4])->avg();11 12// 2
before()
该方法与afterbefore
方法相反。它返回给定项之前的项目。如果未找到给定项或者是第一个项目,则返回:null
1$collection = collect([1, 2, 3, 4, 5]); 2 3$collection->before(3); 4 5// 2 6 7$collection->before(1); 8 9// null10 11collect([2, 4, 6, 8])->before('4', strict: true);12 13// null14 15collect([2, 4, 6, 8])->before(function (int $item, int $key) {16 return $item > 5;17});18 19// 4
chunk()
该chunk
方法将集合分成多个给定大小的较小集合:
1$collection = collect([1, 2, 3, 4, 5, 6, 7]);2 3$chunks = $collection->chunk(4);4 5$chunks->all();6 7// [[1, 2, 3, 4], [5, 6, 7]]
在使用Bootstrap等网格系统时,此方法在视图中特别有用。例如,假设您有一组Eloquent模型,想要在网格中显示:
1@foreach ($products->chunk(3) as $chunk)2 <div class="row">3 @foreach ($chunk as $product)4 <div class="col-xs-4">{{ $product->name }}</div>5 @endforeach6 </div>7@endforeach
chunkWhile()
该chunkWhile
方法根据给定回调的执行结果将集合拆分为多个较小的集合。$chunk
传递给闭包的变量可用于检查前一个元素:
1$collection = collect(str_split('AABBCCCD'));2 3$chunks = $collection->chunkWhile(function (string $value, int $key, Collection $chunk) {4 return $value === $chunk->last();5});6 7$chunks->all();8 9// [['A', 'A'], ['B', 'B'], ['C', 'C', 'C'], ['D']]
collapse()
该collapse
方法将数组或集合的集合折叠为单个平面集合:
1$collection = collect([ 2 [1, 2, 3], 3 [4, 5, 6], 4 [7, 8, 9], 5]); 6 7$collapsed = $collection->collapse(); 8 9$collapsed->all();10 11// [1, 2, 3, 4, 5, 6, 7, 8, 9]
collapseWithKeys()
该collapseWithKeys
方法将数组或集合的集合展平为单个集合,同时保持原始键不变:
1$collection = collect([ 2 ['first' => collect([1, 2, 3])], 3 ['second' => [4, 5, 6]], 4 ['third' => collect([7, 8, 9])] 5]); 6 7$collapsed = $collection->collapseWithKeys(); 8 9$collapsed->all();10 11// [12// 'first' => [1, 2, 3],13// 'second' => [4, 5, 6],14// 'third' => [7, 8, 9],15// ]
collect()
该collect
方法返回一个Collection
包含当前集合中的项目的新实例:
1$collectionA = collect([1, 2, 3]);2 3$collectionB = $collectionA->collect();4 5$collectionB->all();6 7// [1, 2, 3]
该collect
方法主要用于将惰性集合转换为标准Collection
实例:
1$lazyCollection = LazyCollection::make(function () { 2 yield 1; 3 yield 2; 4 yield 3; 5}); 6 7$collection = $lazyCollection->collect(); 8 9$collection::class;10 11// 'Illuminate\Support\Collection'12 13$collection->all();14 15// [1, 2, 3]
collect
当你拥有一个 实例Enumerable
并且需要一个非惰性集合实例时,
该方法尤其有用。由于collect()
是契约的一部分Enumerable
,你可以安全地使用它来获取Collection
实例。
combine()
该combine
方法将集合的值作为键与另一个数组或集合的值组合在一起:
1$collection = collect(['name', 'age']);2 3$combined = $collection->combine(['George', 29]);4 5$combined->all();6 7// ['name' => 'George', 'age' => 29]
concat()
该concat
方法将给定数组或集合的值附加到另一个集合的末尾:
1$collection = collect(['John Doe']);2 3$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);4 5$concatenated->all();6 7// ['John Doe', 'Jane Doe', 'Johnny Doe']
该concat
方法会以数值方式重新索引连接到原始集合中的项的键。要维护关联集合中的键,请参阅merge方法。
contains()
该contains
方法判断集合中是否包含给定项。你可以将闭包传递给该contains
方法,以判断集合中是否存在符合给定真值测试的元素:
1$collection = collect([1, 2, 3, 4, 5]);2 3$collection->contains(function (int $value, int $key) {4 return $value > 5;5});6 7// false
或者,您可以将字符串传递给contains
方法来确定集合是否包含给定的项目值:
1$collection = collect(['name' => 'Desk', 'price' => 100]);2 3$collection->contains('Desk');4 5// true6 7$collection->contains('New York');8 9// false
您还可以将键/值对传递给contains
方法,该方法将确定给定的对是否存在于集合中:
1$collection = collect([2 ['product' => 'Desk', 'price' => 200],3 ['product' => 'Chair', 'price' => 100],4]);5 6$collection->contains('product', 'Bookcase');7 8// false
该contains
方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将被视为等于相同值的整数。使用containsStrict方法可以通过“严格”比较进行筛选。
对于的逆contains
,请参阅doesntContain方法。
containsOneItem()
该containsOneItem
方法确定集合是否包含单个项目:
1collect([])->containsOneItem(); 2 3// false 4 5collect(['1'])->containsOneItem(); 6 7// true 8 9collect(['1', '2'])->containsOneItem();10 11// false12 13collect([1, 2, 3])->containsOneItem(fn (int $item) => $item === 2);14 15// true
containsStrict()
此方法具有与contains方法相同的签名;但是,所有值都使用“严格”比较进行比较。
使用Eloquent Collections时,此方法的行为会被修改。
count()
该count
方法返回集合中的项目总数:
1$collection = collect([1, 2, 3, 4]);2 3$collection->count();4 5// 4
countBy()
该countBy
方法用于统计集合中值的出现次数。默认情况下,该方法会统计每个元素的出现次数,从而允许您统计集合中特定“类型”的元素:
1$collection = collect([1, 2, 2, 2, 3]);2 3$counted = $collection->countBy();4 5$counted->all();6 7// [1 => 1, 2 => 3, 3 => 1]
您可以将闭包传递给countBy
方法,以通过自定义值计算所有项目:
1$collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']);2 3$counted = $collection->countBy(function (string $email) {4 return substr(strrchr($email, '@'), 1);5});6 7$counted->all();8 9// ['gmail.com' => 2, 'yahoo.com' => 1]
crossJoin()
该crossJoin
方法将给定数组或集合中的集合值交叉连接起来,返回具有所有可能排列的笛卡尔积:
1$collection = collect([1, 2]); 2 3$matrix = $collection->crossJoin(['a', 'b']); 4 5$matrix->all(); 6 7/* 8 [ 9 [1, 'a'],10 [1, 'b'],11 [2, 'a'],12 [2, 'b'],13 ]14*/15 16$collection = collect([1, 2]);17 18$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);19 20$matrix->all();21 22/*23 [24 [1, 'a', 'I'],25 [1, 'a', 'II'],26 [1, 'b', 'I'],27 [1, 'b', 'II'],28 [2, 'a', 'I'],29 [2, 'a', 'II'],30 [2, 'b', 'I'],31 [2, 'b', 'II'],32 ]33*/
dd()
该dd
方法转储集合的项目并结束脚本的执行:
1$collection = collect(['John Doe', 'Jane Doe']); 2 3$collection->dd(); 4 5/* 6 array:2 [ 7 0 => "John Doe" 8 1 => "Jane Doe" 9 ]10*/
如果您不想停止执行脚本,请改用dump方法。
diff()
该diff
方法根据集合的值,将集合与另一个集合或纯 PHP 进行比较array
。此方法将返回原始集合中不存在的值:
1$collection = collect([1, 2, 3, 4, 5]);2 3$diff = $collection->diff([2, 4, 6, 8]);4 5$diff->all();6 7// [1, 3, 5]
使用Eloquent Collections时,此方法的行为会被修改。
diffAssoc()
该diffAssoc
方法根据键和值将集合与另一个集合或普通 PHP 进行比较array
。此方法将返回原始集合中不存在的键/值对:
1$collection = collect([ 2 'color' => 'orange', 3 'type' => 'fruit', 4 'remain' => 6, 5]); 6 7$diff = $collection->diffAssoc([ 8 'color' => 'yellow', 9 'type' => 'fruit',10 'remain' => 3,11 'used' => 6,12]);13 14$diff->all();15 16// ['color' => 'orange', 'remain' => 6]
diffAssocUsing()
与 不同diffAssoc
,diffAssocUsing
接受用户提供的回调函数用于索引比较:
1$collection = collect([ 2 'color' => 'orange', 3 'type' => 'fruit', 4 'remain' => 6, 5]); 6 7$diff = $collection->diffAssocUsing([ 8 'Color' => 'yellow', 9 'Type' => 'fruit',10 'Remain' => 3,11], 'strnatcasecmp');12 13$diff->all();14 15// ['color' => 'orange', 'remain' => 6]
回调必须是一个比较函数,返回小于、等于或大于零的整数。有关更多信息,请参阅 PHP 文档中关于array_diff_uassoc 的内容,这是该方法内部使用的 PHP 函数diffAssocUsing
。
diffKeys()
该diffKeys
方法根据键值将集合与另一个集合或普通 PHP 进行比较array
。此方法将返回原始集合中不存在的键/值对:
1$collection = collect([ 2 'one' => 10, 3 'two' => 20, 4 'three' => 30, 5 'four' => 40, 6 'five' => 50, 7]); 8 9$diff = $collection->diffKeys([10 'two' => 2,11 'four' => 4,12 'six' => 6,13 'eight' => 8,14]);15 16$diff->all();17 18// ['one' => 10, 'three' => 30, 'five' => 50]
doesntContain()
该doesntContain
方法判断集合中是否不包含给定项。你可以将闭包传递给该doesntContain
方法,以判断集合中是否存在符合给定真值测试的元素:
1$collection = collect([1, 2, 3, 4, 5]);2 3$collection->doesntContain(function (int $value, int $key) {4 return $value < 5;5});6 7// false
或者,您可以将字符串传递给doesntContain
方法来确定集合是否不包含给定的项目值:
1$collection = collect(['name' => 'Desk', 'price' => 100]);2 3$collection->doesntContain('Table');4 5// true6 7$collection->doesntContain('Desk');8 9// false
您还可以将键/值对传递给doesntContain
方法,该方法将确定给定的对是否在集合中不存在:
1$collection = collect([2 ['product' => 'Desk', 'price' => 200],3 ['product' => 'Chair', 'price' => 100],4]);5 6$collection->doesntContain('product', 'Bookcase');7 8// true
该doesntContain
方法在检查项目值时使用“松散”比较,这意味着具有整数值的字符串将被视为等于相同值的整数。
dot()
该dot
方法将多维集合展平为单级集合,使用“点”符号表示深度:
1$collection = collect(['products' => ['desk' => ['price' => 100]]]);2 3$flattened = $collection->dot();4 5$flattened->all();6 7// ['products.desk.price' => 100]
dump()
该dump
方法转储集合的项目:
1$collection = collect(['John Doe', 'Jane Doe']); 2 3$collection->dump(); 4 5/* 6 array:2 [ 7 0 => "John Doe" 8 1 => "Jane Doe" 9 ]10*/
如果您想在转储集合后停止执行脚本,请使用dd方法。
duplicates()
该duplicates
方法从集合中检索并返回重复的值:
1$collection = collect(['a', 'b', 'a', 'c', 'b']);2 3$collection->duplicates();4 5// [2 => 'a', 4 => 'b']
如果集合包含数组或对象,您可以传递要检查重复值的属性的键:
1$employees = collect([2 ['email' => 'abigail@example.com', 'position' => 'Developer'],3 ['email' => 'james@example.com', 'position' => 'Designer'],4 ['email' => 'victoria@example.com', 'position' => 'Developer'],5]);6 7$employees->duplicates('position');8 9// [2 => 'Developer']
duplicatesStrict()
此方法具有与duplicates方法相同的签名;但是,所有值都使用“严格”比较来进行比较。
each()
该each
方法迭代集合中的项目并将每个项目传递给闭包:
1$collection = collect([1, 2, 3, 4]);2 3$collection->each(function (int $item, int $key) {4 // ...5});
如果您想停止迭代这些项目,您可以false
从闭包中返回:
1$collection->each(function (int $item, int $key) {2 if (/* condition */) {3 return false;4 }5});
eachSpread()
该eachSpread
方法迭代集合的项目,将每个嵌套项目值传递到给定的回调中:
1$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);2 3$collection->eachSpread(function (string $name, int $age) {4 // ...5});
false
您可以通过从回调返回来停止迭代项目:
1$collection->eachSpread(function (string $name, int $age) {2 return false;3});
ensure()
该ensure
方法可用于验证集合中的所有元素是否属于给定类型或类型列表。否则,UnexpectedValueException
将抛出:
1return $collection->ensure(User::class);2 3return $collection->ensure([User::class, Customer::class]);
还可以指定诸如string
、int
、float
、bool
和 之类的原始类型:array
1return $collection->ensure('int');
该ensure
方法不保证稍后不会将不同类型的元素添加到集合中。
every()
该every
方法可用于验证集合中的所有元素是否通过给定的真值测试:
1collect([1, 2, 3, 4])->every(function (int $value, int $key) {2 return $value > 2;3});4 5// false
如果集合为空,该every
方法将返回 true:
1$collection = collect([]);2 3$collection->every(function (int $value, int $key) {4 return $value > 2;5});6 7// true
except()
该except
方法返回集合中除具有指定键的项目之外的所有项目:
1$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);2 3$filtered = $collection->except(['price', 'discount']);4 5$filtered->all();6 7// ['product_id' => 1]
对于 的逆except
,请参见only方法。
使用Eloquent Collections时,此方法的行为会被修改。
filter()
该filter
方法使用给定的回调过滤集合,仅保留通过给定真实性测试的项目:
1$collection = collect([1, 2, 3, 4]);2 3$filtered = $collection->filter(function (int $value, int $key) {4 return $value > 2;5});6 7$filtered->all();8 9// [3, 4]
如果没有提供回调,则集合中所有等同于以下内容的条目false
将被删除:
1$collection = collect([1, 2, 3, null, false, '', 0, []]);2 3$collection->filter()->all();4 5// [1, 2, 3]
对于的逆filter
,请参阅拒绝方法。
first()
该first
方法返回集合中通过给定真值测试的第一个元素:
1collect([1, 2, 3, 4])->first(function (int $value, int $key) {2 return $value > 2;3});4 5// 3
您也可以调用first
不带参数的方法来获取集合中的第一个元素。如果集合为空,null
则返回:
1collect([1, 2, 3, 4])->first();2 3// 1
firstOrFail()
该firstOrFail
方法与方法相同first
;但是,如果没有找到结果,Illuminate\Support\ItemNotFoundException
则会抛出异常:
1collect([1, 2, 3, 4])->firstOrFail(function (int $value, int $key) {2 return $value > 5;3});4 5// Throws ItemNotFoundException...
你也可以调用firstOrFail
不带参数的方法来获取集合中的第一个元素。如果集合为空,Illuminate\Support\ItemNotFoundException
则会抛出异常:
1collect([])->firstOrFail();2 3// Throws ItemNotFoundException...
firstWhere()
该firstWhere
方法返回集合中具有给定键/值对的第一个元素:
1$collection = collect([ 2 ['name' => 'Regena', 'age' => null], 3 ['name' => 'Linda', 'age' => 14], 4 ['name' => 'Diego', 'age' => 23], 5 ['name' => 'Linda', 'age' => 84], 6]); 7 8$collection->firstWhere('name', 'Linda'); 9 10// ['name' => 'Linda', 'age' => 14]
您还可以firstWhere
使用比较运算符调用该方法:
1$collection->firstWhere('age', '>=', 18);2 3// ['name' => 'Diego', 'age' => 23]
与where方法类似,你可以向该方法传递一个参数firstWhere
。在这种情况下,该firstWhere
方法将返回第一个满足给定项键的值为“真”的项:
1$collection->firstWhere('age');2 3// ['name' => 'Linda', 'age' => 14]
flatMap()
该flatMap
方法遍历集合,并将每个值传递给给定的闭包。闭包可以自由修改项并返回,从而形成一个包含已修改项的新集合。然后,数组被展平一级:
1$collection = collect([ 2 ['name' => 'Sally'], 3 ['school' => 'Arkansas'], 4 ['age' => 28] 5]); 6 7$flattened = $collection->flatMap(function (array $values) { 8 return array_map('strtoupper', $values); 9});10 11$flattened->all();12 13// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];
flatten()
该flatten
方法将多维集合展平为单维:
1$collection = collect([ 2 'name' => 'Taylor', 3 'languages' => [ 4 'PHP', 'JavaScript' 5 ] 6]); 7 8$flattened = $collection->flatten(); 9 10$flattened->all();11 12// ['Taylor', 'PHP', 'JavaScript'];
如果有必要,您可以向该flatten
方法传递一个“深度”参数:
1$collection = collect([ 2 'Apple' => [ 3 [ 4 'name' => 'iPhone 6S', 5 'brand' => 'Apple' 6 ], 7 ], 8 'Samsung' => [ 9 [10 'name' => 'Galaxy S7',11 'brand' => 'Samsung'12 ],13 ],14]);15 16$products = $collection->flatten(1);17 18$products->values()->all();19 20/*21 [22 ['name' => 'iPhone 6S', 'brand' => 'Apple'],23 ['name' => 'Galaxy S7', 'brand' => 'Samsung'],24 ]25*/
在此示例中,flatten
如果不提供深度,调用也会展平嵌套数组,结果为['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']
。提供深度允许您指定嵌套数组将被展平的层数。
flip()
该flip
方法将集合的键与其对应的值交换:
1$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);2 3$flipped = $collection->flip();4 5$flipped->all();6 7// ['Taylor' => 'name', 'Laravel' => 'framework']
forget()
该forget
方法根据其键从集合中删除一个项目:
1$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']); 2 3// Forget a single key... 4$collection->forget('name'); 5 6// ['framework' => 'Laravel'] 7 8// Forget multiple keys... 9$collection->forget(['name', 'framework']);10 11// []
与大多数其他集合方法不同,forget
它不会返回新的修改后的集合;它会修改并返回调用它的集合。
forPage()
该forPage
方法返回一个新集合,其中包含给定页码将显示的项目。该方法接受页码作为其第一个参数,每页显示的项目数作为其第二个参数:
1$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);2 3$chunk = $collection->forPage(2, 3);4 5$chunk->all();6 7// [4, 5, 6]
fromJson()
静态fromJson
方法通过使用 PHP 函数解码给定的 JSON 字符串来创建一个新的集合实例json_decode
:
1use Illuminate\Support\Collection;2 3$json = json_encode([4 'name' => 'Taylor Otwell',5 'role' => 'Developer',6 'status' => 'Active',7]);8 9$collection = Collection::fromJson($json);
get()
该get
方法返回指定键对应的项。如果该键不存在,null
则返回:
1$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);2 3$value = $collection->get('name');4 5// Taylor
您可以选择传递默认值作为第二个参数:
1$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);2 3$value = $collection->get('age', 34);4 5// 34
你甚至可以传递一个回调作为方法的默认值。如果指定的键不存在,则返回回调的结果:
1$collection->get('email', function () {2 return 'taylor@example.com';3});4 5// taylor@example.com
groupBy()
该groupBy
方法根据给定的键对集合的项目进行分组:
1$collection = collect([ 2 ['account_id' => 'account-x10', 'product' => 'Chair'], 3 ['account_id' => 'account-x10', 'product' => 'Bookcase'], 4 ['account_id' => 'account-x11', 'product' => 'Desk'], 5]); 6 7$grouped = $collection->groupBy('account_id'); 8 9$grouped->all();10 11/*12 [13 'account-x10' => [14 ['account_id' => 'account-x10', 'product' => 'Chair'],15 ['account_id' => 'account-x10', 'product' => 'Bookcase'],16 ],17 'account-x11' => [18 ['account_id' => 'account-x11', 'product' => 'Desk'],19 ],20 ]21*/
除了传递字符串之外key
,您还可以传递回调函数。回调函数应该返回您希望作为组键的值:
1$grouped = $collection->groupBy(function (array $item, int $key) { 2 return substr($item['account_id'], -3); 3}); 4 5$grouped->all(); 6 7/* 8 [ 9 'x10' => [10 ['account_id' => 'account-x10', 'product' => 'Chair'],11 ['account_id' => 'account-x10', 'product' => 'Bookcase'],12 ],13 'x11' => [14 ['account_id' => 'account-x11', 'product' => 'Desk'],15 ],16 ]17*/
可以将多个分组条件作为数组传递。每个数组元素将应用于多维数组中的相应级别:
1$data = new Collection([ 2 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']], 3 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']], 4 30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']], 5 40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']], 6]); 7 8$result = $data->groupBy(['skill', function (array $item) { 9 return $item['roles'];10}], preserveKeys: true);11 12/*13[14 1 => [15 'Role_1' => [16 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],17 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],18 ],19 'Role_2' => [20 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],21 ],22 'Role_3' => [23 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],24 ],25 ],26 2 => [27 'Role_1' => [28 30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],29 ],30 'Role_2' => [31 40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],32 ],33 ],34];35*/
has()
该has
方法确定集合中是否存在给定的键:
1$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]); 2 3$collection->has('product'); 4 5// true 6 7$collection->has(['product', 'amount']); 8 9// true10 11$collection->has(['amount', 'price']);12 13// false
hasAny()
该hasAny
方法确定集合中是否存在任何给定的键:
1$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);2 3$collection->hasAny(['product', 'price']);4 5// true6 7$collection->hasAny(['name', 'price']);8 9// false
implode()
该implode
方法用于连接集合中的项。其参数取决于集合中项的类型。如果集合包含数组或对象,则应传递要连接的属性的键,以及要在值之间放置的“粘合”字符串:
1$collection = collect([2 ['account_id' => 1, 'product' => 'Desk'],3 ['account_id' => 2, 'product' => 'Chair'],4]);5 6$collection->implode('product', ', ');7 8// 'Desk, Chair'
如果集合包含简单的字符串或数字值,则应将“glue”作为方法的唯一参数传递:
1collect([1, 2, 3, 4, 5])->implode('-');2 3// '1-2-3-4-5'
implode
如果您想要格式化被分解的值,您可以将闭包传递给方法:
1$collection->implode(function (array $item, int $key) {2 return strtoupper($item['product']);3}, ', ');4 5// 'DESK, CHAIR'
intersect()
该intersect
方法将从原始集合中删除所有在给定数组或集合中不存在的值。生成的集合将保留原始集合的键:
1$collection = collect(['Desk', 'Sofa', 'Chair']);2 3$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);4 5$intersect->all();6 7// [0 => 'Desk', 2 => 'Chair']
使用Eloquent Collections时,此方法的行为会被修改。
intersectUsing()
该intersectUsing
方法将从原始集合中删除所有在给定数组或集合中不存在的值,并使用自定义回调来比较这些值。生成的集合将保留原始集合的键:
1$collection = collect(['Desk', 'Sofa', 'Chair']);2 3$intersect = $collection->intersectUsing(['desk', 'chair', 'bookcase'], function (string $a, string $b) {4 return strcasecmp($a, $b);5});6 7$intersect->all();8 9// [0 => 'Desk', 2 => 'Chair']
intersectAssoc()
该intersectAssoc
方法将原始集合与另一个集合或数组进行比较,返回所有给定集合中存在的键/值对:
1$collection = collect([ 2 'color' => 'red', 3 'size' => 'M', 4 'material' => 'cotton' 5]); 6 7$intersect = $collection->intersectAssoc([ 8 'color' => 'blue', 9 'size' => 'M',10 'material' => 'polyester'11]);12 13$intersect->all();14 15// ['size' => 'M']
intersectAssocUsing()
该intersectAssocUsing
方法将原始集合与另一个集合或数组进行比较,返回两者中都存在的键/值对,并使用自定义比较回调来确定键和值是否相等:
1$collection = collect([ 2 'color' => 'red', 3 'Size' => 'M', 4 'material' => 'cotton', 5]); 6 7$intersect = $collection->intersectAssocUsing([ 8 'color' => 'blue', 9 'size' => 'M',10 'material' => 'polyester',11], function (string $a, string $b) {12 return strcasecmp($a, $b);13});14 15$intersect->all();16 17// ['Size' => 'M']
intersectByKeys()
该intersectByKeys
方法从原始集合中删除给定数组或集合中不存在的任何键及其对应的值:
1$collection = collect([ 2 'serial' => 'UX301', 'type' => 'screen', 'year' => 2009, 3]); 4 5$intersect = $collection->intersectByKeys([ 6 'reference' => 'UX404', 'type' => 'tab', 'year' => 2011, 7]); 8 9$intersect->all();10 11// ['type' => 'screen', 'year' => 2009]
isEmpty()
如果集合为空,则该isEmpty
方法返回;否则,返回:true
false
1collect([])->isEmpty();2 3// true
isNotEmpty()
如果集合不为空,则该isNotEmpty
方法返回;否则,返回:true
false
1collect([])->isNotEmpty();2 3// false
join()
该join
方法将集合的值与字符串连接起来。使用此方法的第二个参数,你还可以指定如何将最后一个元素附加到字符串:
1collect(['a', 'b', 'c'])->join(', '); // 'a, b, c'2collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'3collect(['a', 'b'])->join(', ', ' and '); // 'a and b'4collect(['a'])->join(', ', ' and '); // 'a'5collect([])->join(', ', ' and '); // ''
keyBy()
该keyBy
方法使用给定的键来设置集合的键。如果多个项目具有相同的键,则只有最后一个项目会出现在新集合中:
1$collection = collect([ 2 ['product_id' => 'prod-100', 'name' => 'Desk'], 3 ['product_id' => 'prod-200', 'name' => 'Chair'], 4]); 5 6$keyed = $collection->keyBy('product_id'); 7 8$keyed->all(); 9 10/*11 [12 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],13 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],14 ]15*/
你也可以将回调传递给该方法。回调应该返回用于设置集合键的值:
1$keyed = $collection->keyBy(function (array $item, int $key) { 2 return strtoupper($item['product_id']); 3}); 4 5$keyed->all(); 6 7/* 8 [ 9 'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],10 'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],11 ]12*/
keys()
该keys
方法返回集合的所有键:
1$collection = collect([ 2 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], 3 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], 4]); 5 6$keys = $collection->keys(); 7 8$keys->all(); 9 10// ['prod-100', 'prod-200']
last()
该last
方法返回集合中通过给定真值测试的最后一个元素:
1collect([1, 2, 3, 4])->last(function (int $value, int $key) {2 return $value < 3;3});4 5// 2
您也可以调用last
不带参数的方法来获取集合中的最后一个元素。如果集合为空,null
则返回:
1collect([1, 2, 3, 4])->last();2 3// 4
lazy()
该方法从底层项目数组lazy
返回一个新的LazyCollection实例:
1$lazyCollection = collect([1, 2, 3, 4])->lazy();2 3$lazyCollection::class;4 5// Illuminate\Support\LazyCollection6 7$lazyCollection->all();8 9// [1, 2, 3, 4]
当您需要对包含许多项目的巨大文件执行转换时,这尤其有用Collection
:
1$count = $hugeCollection2 ->lazy()3 ->where('country', 'FR')4 ->where('balance', '>', '100')5 ->count();
通过将集合转换为LazyCollection
,我们避免了分配大量额外内存。虽然原始集合仍将其值保留在内存中,但后续的过滤器不会这样做。因此,在过滤集合的结果时几乎不会分配额外的内存。
macro()
静态macro
方法允许您在运行时向类添加方法。有关更多信息,请参阅扩展集合的Collection
文档。
make()
该静态make
方法创建一个新的集合实例。请参阅创建集合部分。
1use Illuminate\Support\Collection;2 3$collection = Collection::make([1, 2, 3]);
map()
该map
方法遍历集合,并将每个值传递给给定的回调。回调可以自由修改该项并将其返回,从而形成一个新的已修改项集合:
1$collection = collect([1, 2, 3, 4, 5]);2 3$multiplied = $collection->map(function (int $item, int $key) {4 return $item * 2;5});6 7$multiplied->all();8 9// [2, 4, 6, 8, 10]
与大多数其他集合方法一样,map
返回一个新的集合实例;它不会修改调用它的集合。如果要转换原始集合,请使用transform方法。
mapInto()
该mapInto()
方法遍历集合,通过将值传递给构造函数来创建给定类的新实例:
1class Currency 2{ 3 /** 4 * Create a new currency instance. 5 */ 6 function __construct( 7 public string $code, 8 ) {} 9}10 11$collection = collect(['USD', 'EUR', 'GBP']);12 13$currencies = $collection->mapInto(Currency::class);14 15$currencies->all();16 17// [Currency('USD'), Currency('EUR'), Currency('GBP')]
mapSpread()
该mapSpread
方法迭代集合中的项,并将每个嵌套项的值传递给给定的闭包。闭包可以自由修改项并将其返回,从而形成一个包含已修改项的新集合:
1$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); 2 3$chunks = $collection->chunk(2); 4 5$sequence = $chunks->mapSpread(function (int $even, int $odd) { 6 return $even + $odd; 7}); 8 9$sequence->all();10 11// [1, 5, 9, 13, 17]
mapToGroups()
该mapToGroups
方法通过给定的闭包对集合中的项目进行分组。闭包应返回一个包含单个键/值对的关联数组,从而形成一个新的分组值集合:
1$collection = collect([ 2 [ 3 'name' => 'John Doe', 4 'department' => 'Sales', 5 ], 6 [ 7 'name' => 'Jane Doe', 8 'department' => 'Sales', 9 ],10 [11 'name' => 'Johnny Doe',12 'department' => 'Marketing',13 ]14]);15 16$grouped = $collection->mapToGroups(function (array $item, int $key) {17 return [$item['department'] => $item['name']];18});19 20$grouped->all();21 22/*23 [24 'Sales' => ['John Doe', 'Jane Doe'],25 'Marketing' => ['Johnny Doe'],26 ]27*/28 29$grouped->get('Sales')->all();30 31// ['John Doe', 'Jane Doe']
mapWithKeys()
该mapWithKeys
方法遍历集合并将每个值传递给给定的回调。回调应该返回一个包含单个键/值对的关联数组:
1$collection = collect([ 2 [ 3 'name' => 'John', 4 'department' => 'Sales', 5 'email' => 'john@example.com', 6 ], 7 [ 8 'name' => 'Jane', 9 'department' => 'Marketing',10 'email' => 'jane@example.com',11 ]12]);13 14$keyed = $collection->mapWithKeys(function (array $item, int $key) {15 return [$item['email'] => $item['name']];16});17 18$keyed->all();19 20/*21 [22 'john@example.com' => 'John',23 'jane@example.com' => 'Jane',24 ]25*/
max()
该max
方法返回给定键的最大值:
1$max = collect([ 2 ['foo' => 10], 3 ['foo' => 20] 4])->max('foo'); 5 6// 20 7 8$max = collect([1, 2, 3, 4, 5])->max(); 9 10// 5
median()
该median
方法返回给定键的中值:
1$median = collect([ 2 ['foo' => 10], 3 ['foo' => 10], 4 ['foo' => 20], 5 ['foo' => 40] 6])->median('foo'); 7 8// 15 9 10$median = collect([1, 1, 2, 4])->median();11 12// 1.5
merge()
该merge
方法将给定的数组或集合与原始集合合并。如果给定项中的字符串键与原始集合中的字符串键匹配,则给定项的值将覆盖原始集合中的值:
1$collection = collect(['product_id' => 1, 'price' => 100]);2 3$merged = $collection->merge(['price' => 200, 'discount' => false]);4 5$merged->all();6 7// ['product_id' => 1, 'price' => 200, 'discount' => false]
如果给定项目的键是数字,则值将附加到集合的末尾:
1$collection = collect(['Desk', 'Chair']);2 3$merged = $collection->merge(['Bookcase', 'Door']);4 5$merged->all();6 7// ['Desk', 'Chair', 'Bookcase', 'Door']
mergeRecursive()
该mergeRecursive
方法将给定的数组或集合递归地与原始集合合并。如果给定项中的字符串键与原始集合中的字符串键匹配,则将这些键的值合并到一个数组中,并以递归方式执行:
1$collection = collect(['product_id' => 1, 'price' => 100]); 2 3$merged = $collection->mergeRecursive([ 4 'product_id' => 2, 5 'price' => 200, 6 'discount' => false 7]); 8 9$merged->all();10 11// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]
min()
该min
方法返回给定键的最小值:
1$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');2 3// 104 5$min = collect([1, 2, 3, 4, 5])->min();6 7// 1
mode()
该mode
方法返回给定键的模式值:
1$mode = collect([ 2 ['foo' => 10], 3 ['foo' => 10], 4 ['foo' => 20], 5 ['foo' => 40] 6])->mode('foo'); 7 8// [10] 9 10$mode = collect([1, 1, 2, 4])->mode();11 12// [1]13 14$mode = collect([1, 1, 2, 2])->mode();15 16// [1, 2]
multiply()
该multiply
方法创建集合中所有项目的指定数量的副本:
1$users = collect([ 2 ['name' => 'User #1', 'email' => 'user1@example.com'], 3 ['name' => 'User #2', 'email' => 'user2@example.com'], 4])->multiply(3); 5 6/* 7 [ 8 ['name' => 'User #1', 'email' => 'user1@example.com'], 9 ['name' => 'User #2', 'email' => 'user2@example.com'],10 ['name' => 'User #1', 'email' => 'user1@example.com'],11 ['name' => 'User #2', 'email' => 'user2@example.com'],12 ['name' => 'User #1', 'email' => 'user1@example.com'],13 ['name' => 'User #2', 'email' => 'user2@example.com'],14 ]15*/
nth()
该nth
方法创建一个由每第 n 个元素组成的新集合:
1$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);2 3$collection->nth(4);4 5// ['a', 'e']
您可以选择传递起始偏移量作为第二个参数:
1$collection->nth(4, 1);2 3// ['b', 'f']
only()
该only
方法返回集合中具有指定键的项目:
1$collection = collect([ 2 'product_id' => 1, 3 'name' => 'Desk', 4 'price' => 100, 5 'discount' => false 6]); 7 8$filtered = $collection->only(['product_id', 'name']); 9 10$filtered->all();11 12// ['product_id' => 1, 'name' => 'Desk']
对于的逆only
,请参见except方法。
使用Eloquent Collections时,此方法的行为会被修改。
pad()
该pad
方法将使用给定值填充数组,直到达到指定大小。此方法的行为类似于PHP 函数array_pad。
要向左填充,应指定负数大小。如果给定大小的绝对值小于或等于数组的长度,则不会进行填充:
1$collection = collect(['A', 'B', 'C']); 2 3$filtered = $collection->pad(5, 0); 4 5$filtered->all(); 6 7// ['A', 'B', 'C', 0, 0] 8 9$filtered = $collection->pad(-5, 0);10 11$filtered->all();12 13// [0, 0, 'A', 'B', 'C']
partition()
该partition
方法可以与 PHP 数组解构相结合,将通过给定真值测试的元素与未通过给定真值测试的元素分开:
1$collection = collect([1, 2, 3, 4, 5, 6]); 2 3[$underThree, $equalOrAboveThree] = $collection->partition(function (int $i) { 4 return $i < 3; 5}); 6 7$underThree->all(); 8 9// [1, 2]10 11$equalOrAboveThree->all();12 13// [3, 4, 5, 6]
与Eloquent 集合 交互时,此方法的行为会被修改。
percentage()
该percentage
方法可用于快速确定集合中通过给定真实性测试的项目的百分比:
1$collection = collect([1, 1, 2, 2, 2, 3]);2 3$percentage = $collection->percentage(fn (int $value) => $value === 1);4 5// 33.33
默认情况下,百分比将四舍五入到小数点后两位。但是,你可以通过为该方法提供第二个参数来自定义此行为:
1$percentage = $collection->percentage(fn (int $value) => $value === 1, precision: 3);2 3// 33.333
pipe()
该pipe
方法将集合传递给给定的闭包并返回执行闭包的结果:
1$collection = collect([1, 2, 3]);2 3$piped = $collection->pipe(function (Collection $collection) {4 return $collection->sum();5});6 7// 6
pipeInto()
该pipeInto
方法创建给定类的新实例并将集合传递给构造函数:
1class ResourceCollection 2{ 3 /** 4 * Create a new ResourceCollection instance. 5 */ 6 public function __construct( 7 public Collection $collection, 8 ) {} 9}10 11$collection = collect([1, 2, 3]);12 13$resource = $collection->pipeInto(ResourceCollection::class);14 15$resource->collection->all();16 17// [1, 2, 3]
pipeThrough()
该pipeThrough
方法将集合传递给给定的闭包数组并返回执行闭包的结果:
1use Illuminate\Support\Collection; 2 3$collection = collect([1, 2, 3]); 4 5$result = $collection->pipeThrough([ 6 function (Collection $collection) { 7 return $collection->merge([4, 5]); 8 }, 9 function (Collection $collection) {10 return $collection->sum();11 },12]);13 14// 15
pluck()
该pluck
方法检索给定键的所有值:
1$collection = collect([ 2 ['product_id' => 'prod-100', 'name' => 'Desk'], 3 ['product_id' => 'prod-200', 'name' => 'Chair'], 4]); 5 6$plucked = $collection->pluck('name'); 7 8$plucked->all(); 9 10// ['Desk', 'Chair']
您还可以指定结果集合的键值:
1$plucked = $collection->pluck('name', 'product_id');2 3$plucked->all();4 5// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
该pluck
方法还支持使用“点”符号检索嵌套值:
1$collection = collect([ 2 [ 3 'name' => 'Laracon', 4 'speakers' => [ 5 'first_day' => ['Rosa', 'Judith'], 6 ], 7 ], 8 [ 9 'name' => 'VueConf',10 'speakers' => [11 'first_day' => ['Abigail', 'Joey'],12 ],13 ],14]);15 16$plucked = $collection->pluck('speakers.first_day');17 18$plucked->all();19 20// [['Rosa', 'Judith'], ['Abigail', 'Joey']]
如果存在重复的键,则最后一个匹配的元素将被插入到挑选的集合中:
1$collection = collect([ 2 ['brand' => 'Tesla', 'color' => 'red'], 3 ['brand' => 'Pagani', 'color' => 'white'], 4 ['brand' => 'Tesla', 'color' => 'black'], 5 ['brand' => 'Pagani', 'color' => 'orange'], 6]); 7 8$plucked = $collection->pluck('color', 'brand'); 9 10$plucked->all();11 12// ['Tesla' => 'black', 'Pagani' => 'orange']
pop()
该pop
方法从集合中移除并返回最后一个元素。如果集合为空,null
则返回:
1$collection = collect([1, 2, 3, 4, 5]);2 3$collection->pop();4 5// 56 7$collection->all();8 9// [1, 2, 3, 4]
您可以将整数传递给pop
方法以从集合末尾删除并返回多个项目:
1$collection = collect([1, 2, 3, 4, 5]);2 3$collection->pop(3);4 5// collect([5, 4, 3])6 7$collection->all();8 9// [1, 2]
prepend()
该prepend
方法将一个项目添加到集合的开头:
1$collection = collect([1, 2, 3, 4, 5]);2 3$collection->prepend(0);4 5$collection->all();6 7// [0, 1, 2, 3, 4, 5]
您还可以传递第二个参数来指定前置项目的键:
1$collection = collect(['one' => 1, 'two' => 2]);2 3$collection->prepend(0, 'zero');4 5$collection->all();6 7// ['zero' => 0, 'one' => 1, 'two' => 2]
pull()
该pull
方法通过其键从集合中删除并返回一个项目:
1$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);2 3$collection->pull('name');4 5// 'Desk'6 7$collection->all();8 9// ['product_id' => 'prod-100']
push()
该push
方法将一个项目附加到集合的末尾:
1$collection = collect([1, 2, 3, 4]);2 3$collection->push(5);4 5$collection->all();6 7// [1, 2, 3, 4, 5]
put()
该put
方法设置集合中给定的键和值:
1$collection = collect(['product_id' => 1, 'name' => 'Desk']);2 3$collection->put('price', 100);4 5$collection->all();6 7// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
random()
该random
方法从集合中返回一个随机项:
1$collection = collect([1, 2, 3, 4, 5]);2 3$collection->random();4 5// 4 - (retrieved randomly)
您可以传递一个整数来random
指定要随机检索的项目数量。明确传递您希望接收的项目数量时,始终会返回项目集合:
1$random = $collection->random(3);2 3$random->all();4 5// [2, 4, 5] - (retrieved randomly)
如果集合实例的项目数少于请求的项目数,则该random
方法将抛出一个InvalidArgumentException
。
该random
方法还接受一个闭包,它将接收当前的集合实例:
1use Illuminate\Support\Collection;2 3$random = $collection->random(fn (Collection $items) => min(10, count($items)));4 5$random->all();6 7// [1, 2, 3, 4, 5] - (retrieved randomly)
range()
该range
方法返回包含指定范围内的整数的集合:
1$collection = collect()->range(3, 6);2 3$collection->all();4 5// [3, 4, 5, 6]
reduce()
该reduce
方法将集合简化为单个值,并将每次迭代的结果传递到后续迭代中:
1$collection = collect([1, 2, 3]);2 3$total = $collection->reduce(function (?int $carry, int $item) {4 return $carry + $item;5});6 7// 6
$carry
第一次迭代的值为null
;但是,您可以通过将第二个参数传递给来指定其初始值reduce
:
1$collection->reduce(function (int $carry, int $item) {2 return $carry + $item;3}, 4);4 5// 10
该reduce
方法还将数组键传递给给定的回调:
1$collection = collect([ 2 'usd' => 1400, 3 'gbp' => 1200, 4 'eur' => 1000, 5]); 6 7$ratio = [ 8 'usd' => 1, 9 'gbp' => 1.37,10 'eur' => 1.22,11];12 13$collection->reduce(function (int $carry, int $value, string $key) use ($ratio) {14 return $carry + ($value * $ratio[$key]);15}, 0);16 17// 4264
reduceSpread()
该reduceSpread
方法将集合简化为一个值数组,并将每次迭代的结果传递给后续迭代。此方法与reduce
方法类似;但是,它可以接受多个初始值:
1[$creditsRemaining, $batch] = Image::where('status', 'unprocessed') 2 ->get() 3 ->reduceSpread(function (int $creditsRemaining, Collection $batch, Image $image) { 4 if ($creditsRemaining >= $image->creditsRequired()) { 5 $batch->push($image); 6 7 $creditsRemaining -= $image->creditsRequired(); 8 } 9 10 return [$creditsRemaining, $batch];11 }, $creditsAvailable, collect());
reject()
该reject
方法使用给定的闭包过滤集合。true
如果要从结果集合中删除该项,则闭包应该返回:
1$collection = collect([1, 2, 3, 4]);2 3$filtered = $collection->reject(function (int $value, int $key) {4 return $value > 2;5});6 7$filtered->all();8 9// [1, 2]
对于该方法的逆方法reject
,请参阅过滤方法。
replace()
该replace
方法的行为类似于merge
;但是,除了覆盖具有字符串键的匹配项之外,该replace
方法还将覆盖集合中具有匹配数字键的项:
1$collection = collect(['Taylor', 'Abigail', 'James']);2 3$replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']);4 5$replaced->all();6 7// ['Taylor', 'Victoria', 'James', 'Finn']
replaceRecursive()
该replaceRecursive
方法的行为与类似replace
,但它会递归到数组中并对内部值应用相同的替换过程:
1$collection = collect([ 2 'Taylor', 3 'Abigail', 4 [ 5 'James', 6 'Victoria', 7 'Finn' 8 ] 9]);10 11$replaced = $collection->replaceRecursive([12 'Charlie',13 2 => [1 => 'King']14]);15 16$replaced->all();17 18// ['Charlie', 'Abigail', ['James', 'King', 'Finn']]
reverse()
该reverse
方法反转集合项目的顺序,保留原始键:
1$collection = collect(['a', 'b', 'c', 'd', 'e']); 2 3$reversed = $collection->reverse(); 4 5$reversed->all(); 6 7/* 8 [ 9 4 => 'e',10 3 => 'd',11 2 => 'c',12 1 => 'b',13 0 => 'a',14 ]15*/
search()
该search
方法在集合中搜索给定的值,如果找到则返回其键。如果未找到该项,false
则返回:
1$collection = collect([2, 4, 6, 8]);2 3$collection->search(4);4 5// 1
搜索使用“松散”比较,这意味着具有整数值的字符串将被视为等于相同值的整数。要使用“严格”比较,请将true
第二个参数传递给该方法:
1collect([2, 4, 6, 8])->search('4', strict: true);2 3// false
或者,您可以提供自己的闭包来搜索通过给定真实性测试的第一个项目:
1collect([2, 4, 6, 8])->search(function (int $item, int $key) {2 return $item > 5;3});4 5// 2
select()
该select
方法从集合中选择给定的键,类似于 SQLSELECT
语句:
1$users = collect([ 2 ['name' => 'Taylor Otwell', 'role' => 'Developer', 'status' => 'active'], 3 ['name' => 'Victoria Faith', 'role' => 'Researcher', 'status' => 'active'], 4]); 5 6$users->select(['name', 'role']); 7 8/* 9 [10 ['name' => 'Taylor Otwell', 'role' => 'Developer'],11 ['name' => 'Victoria Faith', 'role' => 'Researcher'],12 ],13*/
shift()
该shift
方法从集合中删除并返回第一个项目:
1$collection = collect([1, 2, 3, 4, 5]);2 3$collection->shift();4 5// 16 7$collection->all();8 9// [2, 3, 4, 5]
您可以将整数传递给shift
方法以从集合的开头删除并返回多个项目:
1$collection = collect([1, 2, 3, 4, 5]);2 3$collection->shift(3);4 5// collect([1, 2, 3])6 7$collection->all();8 9// [4, 5]
shuffle()
该shuffle
方法随机打乱集合中的项目:
1$collection = collect([1, 2, 3, 4, 5]);2 3$shuffled = $collection->shuffle();4 5$shuffled->all();6 7// [3, 2, 5, 1, 4] - (generated randomly)
skip()
该skip
方法返回一个新集合,其中从集合开头删除了给定数量的元素:
1$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);2 3$collection = $collection->skip(4);4 5$collection->all();6 7// [5, 6, 7, 8, 9, 10]
skipUntil()
当给定的回调返回时,该skipUntil
方法会跳过集合中的项目false
。回调返回后,true
集合中所有剩余的项目将作为新集合返回:
1$collection = collect([1, 2, 3, 4]);2 3$subset = $collection->skipUntil(function (int $item) {4 return $item >= 3;5});6 7$subset->all();8 9// [3, 4]
您还可以向skipUntil
方法传递一个简单的值来跳过所有项目,直到找到给定的值:
1$collection = collect([1, 2, 3, 4]);2 3$subset = $collection->skipUntil(3);4 5$subset->all();6 7// [3, 4]
如果未找到给定的值或回调从未返回true
,则该skipUntil
方法将返回一个空集合。
skipWhile()
当给定的回调返回时,该skipWhile
方法会跳过集合中的项目true
。回调返回后,false
集合中所有剩余的项目将作为新集合返回:
1$collection = collect([1, 2, 3, 4]);2 3$subset = $collection->skipWhile(function (int $item) {4 return $item <= 3;5});6 7$subset->all();8 9// [4]
如果回调从未返回false
,则该skipWhile
方法将返回一个空集合。
slice()
该slice
方法返回从给定索引开始的集合片段:
1$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);2 3$slice = $collection->slice(4);4 5$slice->all();6 7// [5, 6, 7, 8, 9, 10]
如果您想限制返回切片的大小,请将所需大小作为第二个参数传递给方法:
1$slice = $collection->slice(4, 2);2 3$slice->all();4 5// [5, 6]
返回的切片默认会保留键。如果你不想保留原始键,可以使用values方法重新索引它们。
sliding()
该sliding
方法返回一个新的块集合,表示集合中项目的“滑动窗口”视图:
1$collection = collect([1, 2, 3, 4, 5]);2 3$chunks = $collection->sliding(2);4 5$chunks->toArray();6 7// [[1, 2], [2, 3], [3, 4], [4, 5]]
这与eachSpread方法结合使用特别有用:
1$transactions->sliding(2)->eachSpread(function (Collection $previous, Collection $current) {2 $current->total = $previous->total + $current->amount;3});
您可以选择传递第二个“步长”值,该值决定每个块的第一个项目之间的距离:
1$collection = collect([1, 2, 3, 4, 5]);2 3$chunks = $collection->sliding(3, step: 2);4 5$chunks->toArray();6 7// [[1, 2, 3], [3, 4, 5]]
sole()
该sole
方法返回集合中通过给定真值测试的第一个元素,但前提是真值测试与一个元素完全匹配:
1collect([1, 2, 3, 4])->sole(function (int $value, int $key) {2 return $value === 2;3});4 5// 2
您还可以将键/值对传递给该sole
方法,该方法将返回集合中与给定对匹配的第一个元素,但前提是恰好有一个元素匹配:
1$collection = collect([2 ['product' => 'Desk', 'price' => 200],3 ['product' => 'Chair', 'price' => 100],4]);5 6$collection->sole('product', 'Chair');7 8// ['product' => 'Chair', 'price' => 100]
sole
或者,如果只有一个元素,您也可以调用不带参数的方法来获取集合中的第一个元素:
1$collection = collect([2 ['product' => 'Desk', 'price' => 200],3]);4 5$collection->sole();6 7// ['product' => 'Desk', 'price' => 200]
如果该方法返回的集合中没有元素sole
,\Illuminate\Collections\ItemNotFoundException
则会抛出异常。如果返回的元素多于一个,\Illuminate\Collections\MultipleItemsFoundException
则会抛出异常。
some()
contains方法的别名。
sort()
该sort
方法对集合进行排序。排序后的集合保留原始数组键,因此在下面的示例中,我们将使用values方法将键重置为连续编号的索引:
1$collection = collect([5, 3, 1, 2, 4]);2 3$sorted = $collection->sort();4 5$sorted->values()->all();6 7// [1, 2, 3, 4, 5]
如果您需要更高级的排序功能,可以传递一个回调函数,sort
其中包含您自己的算法。请参阅 PHP 文档中关于uasort 的内容,该函数是集合sort
方法调用内部使用的。
如果需要对嵌套数组或对象的集合进行排序,请参阅sortBy和sortByDesc方法。
sortBy()
该sortBy
方法根据给定的键对集合进行排序。排序后的集合保留原始数组键,因此在下面的示例中,我们将使用values方法将键重置为连续编号的索引:
1$collection = collect([ 2 ['name' => 'Desk', 'price' => 200], 3 ['name' => 'Chair', 'price' => 100], 4 ['name' => 'Bookcase', 'price' => 150], 5]); 6 7$sorted = $collection->sortBy('price'); 8 9$sorted->values()->all();10 11/*12 [13 ['name' => 'Chair', 'price' => 100],14 ['name' => 'Bookcase', 'price' => 150],15 ['name' => 'Desk', 'price' => 200],16 ]17*/
该sortBy
方法接受排序标志作为其第二个参数:
1$collection = collect([ 2 ['title' => 'Item 1'], 3 ['title' => 'Item 12'], 4 ['title' => 'Item 3'], 5]); 6 7$sorted = $collection->sortBy('title', SORT_NATURAL); 8 9$sorted->values()->all();10 11/*12 [13 ['title' => 'Item 1'],14 ['title' => 'Item 3'],15 ['title' => 'Item 12'],16 ]17*/
或者,您可以传递自己的闭包来确定如何对集合的值进行排序:
1$collection = collect([ 2 ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']], 3 ['name' => 'Chair', 'colors' => ['Black']], 4 ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']], 5]); 6 7$sorted = $collection->sortBy(function (array $product, int $key) { 8 return count($product['colors']); 9});10 11$sorted->values()->all();12 13/*14 [15 ['name' => 'Chair', 'colors' => ['Black']],16 ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],17 ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],18 ]19*/
如果您想按多个属性对集合进行排序,可以将一个排序操作数组传递给该sortBy
方法。每个排序操作都应该是一个数组,其中包含您希望排序的属性以及所需的排序方向:
1$collection = collect([ 2 ['name' => 'Taylor Otwell', 'age' => 34], 3 ['name' => 'Abigail Otwell', 'age' => 30], 4 ['name' => 'Taylor Otwell', 'age' => 36], 5 ['name' => 'Abigail Otwell', 'age' => 32], 6]); 7 8$sorted = $collection->sortBy([ 9 ['name', 'asc'],10 ['age', 'desc'],11]);12 13$sorted->values()->all();14 15/*16 [17 ['name' => 'Abigail Otwell', 'age' => 32],18 ['name' => 'Abigail Otwell', 'age' => 30],19 ['name' => 'Taylor Otwell', 'age' => 36],20 ['name' => 'Taylor Otwell', 'age' => 34],21 ]22*/
当按多个属性对集合进行排序时,您还可以提供定义每个排序操作的闭包:
1$collection = collect([ 2 ['name' => 'Taylor Otwell', 'age' => 34], 3 ['name' => 'Abigail Otwell', 'age' => 30], 4 ['name' => 'Taylor Otwell', 'age' => 36], 5 ['name' => 'Abigail Otwell', 'age' => 32], 6]); 7 8$sorted = $collection->sortBy([ 9 fn (array $a, array $b) => $a['name'] <=> $b['name'],10 fn (array $a, array $b) => $b['age'] <=> $a['age'],11]);12 13$sorted->values()->all();14 15/*16 [17 ['name' => 'Abigail Otwell', 'age' => 32],18 ['name' => 'Abigail Otwell', 'age' => 30],19 ['name' => 'Taylor Otwell', 'age' => 36],20 ['name' => 'Taylor Otwell', 'age' => 34],21 ]22*/
sortByDesc()
此方法具有与sortBy方法相同的签名,但将按相反的顺序对集合进行排序。
sortDesc()
此方法将按照与sort方法相反的顺序对集合进行排序:
1$collection = collect([5, 3, 1, 2, 4]);2 3$sorted = $collection->sortDesc();4 5$sorted->values()->all();6 7// [5, 4, 3, 2, 1]
与 不同sort
,你不能将闭包传递给sortDesc
。相反,你应该使用sort方法并反转比较。
sortKeys()
该sortKeys
方法根据底层关联数组的键对集合进行排序:
1$collection = collect([ 2 'id' => 22345, 3 'first' => 'John', 4 'last' => 'Doe', 5]); 6 7$sorted = $collection->sortKeys(); 8 9$sorted->all();10 11/*12 [13 'first' => 'John',14 'id' => 22345,15 'last' => 'Doe',16 ]17*/
sortKeysDesc()
此方法与sortKeys方法具有相同的签名,但将按相反的顺序对集合进行排序。
sortKeysUsing()
该sortKeysUsing
方法使用回调根据底层关联数组的键对集合进行排序:
1$collection = collect([ 2 'ID' => 22345, 3 'first' => 'John', 4 'last' => 'Doe', 5]); 6 7$sorted = $collection->sortKeysUsing('strnatcasecmp'); 8 9$sorted->all();10 11/*12 [13 'first' => 'John',14 'ID' => 22345,15 'last' => 'Doe',16 ]17*/
回调必须是一个比较函数,返回小于、等于或大于零的整数。有关更多信息,请参阅uksortsortKeysUsing
的 PHP 文档,这是该方法内部使用的PHP 函数。
splice()
该splice
方法删除并返回从指定索引开始的项目切片:
1$collection = collect([1, 2, 3, 4, 5]); 2 3$chunk = $collection->splice(2); 4 5$chunk->all(); 6 7// [3, 4, 5] 8 9$collection->all();10 11// [1, 2]
您可以传递第二个参数来限制结果集合的大小:
1$collection = collect([1, 2, 3, 4, 5]); 2 3$chunk = $collection->splice(2, 1); 4 5$chunk->all(); 6 7// [3] 8 9$collection->all();10 11// [1, 2, 4, 5]
此外,您可以传递包含新项目的第三个参数来替换从集合中删除的项目:
1$collection = collect([1, 2, 3, 4, 5]); 2 3$chunk = $collection->splice(2, 1, [10, 11]); 4 5$chunk->all(); 6 7// [3] 8 9$collection->all();10 11// [1, 2, 10, 11, 4, 5]
split()
该split
方法将集合分成给定数量的组:
1$collection = collect([1, 2, 3, 4, 5]);2 3$groups = $collection->split(3);4 5$groups->all();6 7// [[1, 2], [3, 4], [5]]
splitIn()
该splitIn
方法将集合分成给定数量的组,在将剩余部分分配给最后一个组之前,完全填充非终端组:
1$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);2 3$groups = $collection->splitIn(3);4 5$groups->all();6 7// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
sum()
该sum
方法返回集合中所有项目的总和:
1collect([1, 2, 3, 4, 5])->sum();2 3// 15
如果集合包含嵌套数组或对象,则应传递一个键,该键将用于确定要求和的值:
1$collection = collect([2 ['name' => 'JavaScript: The Good Parts', 'pages' => 176],3 ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],4]);5 6$collection->sum('pages');7 8// 1272
此外,您可以传递自己的闭包来确定要对集合中的哪些值进行求和:
1$collection = collect([ 2 ['name' => 'Chair', 'colors' => ['Black']], 3 ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']], 4 ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']], 5]); 6 7$collection->sum(function (array $product) { 8 return count($product['colors']); 9});10 11// 6
take()
该take
方法返回具有指定数量项目的新集合:
1$collection = collect([0, 1, 2, 3, 4, 5]);2 3$chunk = $collection->take(3);4 5$chunk->all();6 7// [0, 1, 2]
您还可以传递一个负整数来从集合末尾获取指定数量的项目:
1$collection = collect([0, 1, 2, 3, 4, 5]);2 3$chunk = $collection->take(-2);4 5$chunk->all();6 7// [4, 5]
takeUntil()
该takeUntil
方法返回集合中的项目,直到给定的回调返回true
:
1$collection = collect([1, 2, 3, 4]);2 3$subset = $collection->takeUntil(function (int $item) {4 return $item >= 3;5});6 7$subset->all();8 9// [1, 2]
您还可以向该takeUntil
方法传递一个简单的值来获取项目,直到找到给定的值:
1$collection = collect([1, 2, 3, 4]);2 3$subset = $collection->takeUntil(3);4 5$subset->all();6 7// [1, 2]
如果未找到给定值或回调从未返回true
,则该takeUntil
方法将返回集合中的所有项目。
takeWhile()
该takeWhile
方法返回集合中的项目,直到给定的回调返回false
:
1$collection = collect([1, 2, 3, 4]);2 3$subset = $collection->takeWhile(function (int $item) {4 return $item < 3;5});6 7$subset->all();8 9// [1, 2]
如果回调永不返回false
,则该takeWhile
方法将返回集合中的所有项目。
tap()
该tap
方法将集合传递给指定的回调函数,允许你在特定时间点“点击”该集合并对其执行某些操作,而不会影响集合本身。然后,该tap
方法将返回该集合:
1collect([2, 4, 3, 1, 5])2 ->sort()3 ->tap(function (Collection $collection) {4 Log::debug('Values after sorting', $collection->values()->all());5 })6 ->shift();7 8// 1
times()
静态times
方法通过调用给定闭包指定次数来创建一个新集合:
1$collection = Collection::times(10, function (int $number) {2 return $number * 9;3});4 5$collection->all();6 7// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
toArray()
该toArray
方法将集合转换为普通的 PHP 对象array
。如果集合的值是Eloquent模型,则模型也会转换为数组:
1$collection = collect(['name' => 'Desk', 'price' => 200]);2 3$collection->toArray();4 5/*6 [7 ['name' => 'Desk', 'price' => 200],8 ]9*/
toArray
还会将集合中所有嵌套的 实例对象转换Arrayable
为数组。如果要获取集合底层的原始数组,请使用all方法。
toJson()
该toJson
方法将集合转换为 JSON 序列化字符串:
1$collection = collect(['name' => 'Desk', 'price' => 200]);2 3$collection->toJson();4 5// '{"name":"Desk", "price":200}'
transform()
该transform
方法遍历集合,并对集合中的每个项目调用给定的回调。集合中的项目将被回调返回的值替换:
1$collection = collect([1, 2, 3, 4, 5]);2 3$collection->transform(function (int $item, int $key) {4 return $item * 2;5});6 7$collection->all();8 9// [2, 4, 6, 8, 10]
与大多数其他集合方法不同,maptransform
方法会修改集合本身。如果您希望创建新集合,请使用map方法。
undot()
该undot
方法将使用“点”符号的单维集合扩展为多维集合:
1$person = collect([ 2 'name.first_name' => 'Marie', 3 'name.last_name' => 'Valentine', 4 'address.line_1' => '2992 Eagle Drive', 5 'address.line_2' => '', 6 'address.suburb' => 'Detroit', 7 'address.state' => 'MI', 8 'address.postcode' => '48219' 9]);10 11$person = $person->undot();12 13$person->toArray();14 15/*16 [17 "name" => [18 "first_name" => "Marie",19 "last_name" => "Valentine",20 ],21 "address" => [22 "line_1" => "2992 Eagle Drive",23 "line_2" => "",24 "suburb" => "Detroit",25 "state" => "MI",26 "postcode" => "48219",27 ],28 ]29*/
union()
该union
方法将给定的数组添加到集合中。如果给定的数组包含原始集合中已经存在的键,则优先使用原始集合的值:
1$collection = collect([1 => ['a'], 2 => ['b']]);2 3$union = $collection->union([3 => ['c'], 1 => ['d']]);4 5$union->all();6 7// [1 => ['a'], 2 => ['b'], 3 => ['c']]
unique()
该unique
方法返回集合中所有不重复的项。返回的集合保留了原始数组键,因此在下面的示例中,我们将使用values方法将键重置为连续编号的索引:
1$collection = collect([1, 1, 2, 2, 3, 4, 2]);2 3$unique = $collection->unique();4 5$unique->values()->all();6 7// [1, 2, 3, 4]
处理嵌套数组或对象时,您可以指定用于确定唯一性的键:
1$collection = collect([ 2 ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], 3 ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'], 4 ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], 5 ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], 6 ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], 7]); 8 9$unique = $collection->unique('brand');10 11$unique->values()->all();12 13/*14 [15 ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],16 ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],17 ]18*/
最后,您还可以将自己的闭包传递给unique
方法来指定哪个值应该决定项目的唯一性:
1$unique = $collection->unique(function (array $item) { 2 return $item['brand'].$item['type']; 3}); 4 5$unique->values()->all(); 6 7/* 8 [ 9 ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],10 ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],11 ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],12 ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],13 ]14*/
该unique
方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将被视为等于相同值的整数。使用uniqueStrict方法可以通过“严格”比较进行筛选。
使用Eloquent Collections时,此方法的行为会被修改。
uniqueStrict()
该方法具有与唯一方法相同的签名;但是,所有值都使用“严格”比较进行比较。
unless()
该unless
方法将执行给定的回调,除非传递给该方法的第一个参数的值为true
。集合实例和传递给该unless
方法的第一个参数将传递给闭包:
1$collection = collect([1, 2, 3]); 2 3$collection->unless(true, function (Collection $collection, bool $value) { 4 return $collection->push(4); 5}); 6 7$collection->unless(false, function (Collection $collection, bool $value) { 8 return $collection->push(5); 9});10 11$collection->all();12 13// [1, 2, 3, 5]
可以将第二个回调传递给该unless
方法。当传递给该方法的第一个参数的unless
值为true
:
1$collection = collect([1, 2, 3]); 2 3$collection->unless(true, function (Collection $collection, bool $value) { 4 return $collection->push(4); 5}, function (Collection $collection, bool $value) { 6 return $collection->push(5); 7}); 8 9$collection->all();10 11// [1, 2, 3, 5]
对于的逆unless
,请参阅when方法。
unlessEmpty()
whenNotEmpty方法的别名。
unlessNotEmpty()
whenEmpty方法的别名。
unwrap()
静态unwrap
方法在适用时从给定值返回集合的基础项目:
1Collection::unwrap(collect('John Doe')); 2 3// ['John Doe'] 4 5Collection::unwrap(['John Doe']); 6 7// ['John Doe'] 8 9Collection::unwrap('John Doe');10 11// 'John Doe'
value()
该value
方法从集合的第一个元素中检索给定值:
1$collection = collect([2 ['product' => 'Desk', 'price' => 200],3 ['product' => 'Speaker', 'price' => 400],4]);5 6$value = $collection->value('price');7 8// 200
values()
该values
方法返回一个新集合,其中的键重置为连续的整数:
1$collection = collect([ 2 10 => ['product' => 'Desk', 'price' => 200], 3 11 => ['product' => 'Desk', 'price' => 200], 4]); 5 6$values = $collection->values(); 7 8$values->all(); 9 10/*11 [12 0 => ['product' => 'Desk', 'price' => 200],13 1 => ['product' => 'Desk', 'price' => 200],14 ]15*/
when()
when
当传递给方法的第一个参数的值为 时,该方法将执行给定的回调true
。集合实例和传递给该when
方法的第一个参数将传递给闭包:
1$collection = collect([1, 2, 3]); 2 3$collection->when(true, function (Collection $collection, bool $value) { 4 return $collection->push(4); 5}); 6 7$collection->when(false, function (Collection $collection, bool $value) { 8 return $collection->push(5); 9});10 11$collection->all();12 13// [1, 2, 3, 4]
可以将第二个回调传递给该when
方法。当传递给该方法的第一个参数的when
值为false
:
1$collection = collect([1, 2, 3]); 2 3$collection->when(false, function (Collection $collection, bool $value) { 4 return $collection->push(4); 5}, function (Collection $collection, bool $value) { 6 return $collection->push(5); 7}); 8 9$collection->all();10 11// [1, 2, 3, 5]
对于 的逆when
,请参阅unless方法。
whenEmpty()
whenEmpty
当集合为空时,该方法将执行给定的回调:
1$collection = collect(['Michael', 'Tom']); 2 3$collection->whenEmpty(function (Collection $collection) { 4 return $collection->push('Adam'); 5}); 6 7$collection->all(); 8 9// ['Michael', 'Tom']10 11$collection = collect();12 13$collection->whenEmpty(function (Collection $collection) {14 return $collection->push('Adam');15});16 17$collection->all();18 19// ['Adam']
可以将第二个闭包传递给whenEmpty
当集合不为空时执行的方法:
1$collection = collect(['Michael', 'Tom']); 2 3$collection->whenEmpty(function (Collection $collection) { 4 return $collection->push('Adam'); 5}, function (Collection $collection) { 6 return $collection->push('Taylor'); 7}); 8 9$collection->all();10 11// ['Michael', 'Tom', 'Taylor']
对于的逆whenEmpty
,请参阅whenNotEmpty方法。
whenNotEmpty()
whenNotEmpty
当集合不为空时,该方法将执行给定的回调:
1$collection = collect(['Michael', 'Tom']); 2 3$collection->whenNotEmpty(function (Collection $collection) { 4 return $collection->push('Adam'); 5}); 6 7$collection->all(); 8 9// ['Michael', 'Tom', 'Adam']10 11$collection = collect();12 13$collection->whenNotEmpty(function (Collection $collection) {14 return $collection->push('Adam');15});16 17$collection->all();18 19// []
可以将第二个闭包传递给whenNotEmpty
当集合为空时执行的方法:
1$collection = collect(); 2 3$collection->whenNotEmpty(function (Collection $collection) { 4 return $collection->push('Adam'); 5}, function (Collection $collection) { 6 return $collection->push('Taylor'); 7}); 8 9$collection->all();10 11// ['Taylor']
对于的逆whenNotEmpty
,请参阅whenEmpty方法。
where()
该where
方法通过给定的键/值对过滤集合:
1$collection = collect([ 2 ['product' => 'Desk', 'price' => 200], 3 ['product' => 'Chair', 'price' => 100], 4 ['product' => 'Bookcase', 'price' => 150], 5 ['product' => 'Door', 'price' => 100], 6]); 7 8$filtered = $collection->where('price', 100); 9 10$filtered->all();11 12/*13 [14 ['product' => 'Chair', 'price' => 100],15 ['product' => 'Door', 'price' => 100],16 ]17*/
该where
方法在检查项目值时使用“松散”比较,这意味着具有整数值的字符串将被视为等于相同值的整数。使用whereStrict方法可以通过“严格”比较进行筛选。
您也可以选择将比较运算符作为第二个参数传递。支持的运算符包括:'==='、'!=='、'!='、'=='、'='、'<>'、'>'、'<'、'>=' 和 '<=':
1$collection = collect([ 2 ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'], 3 ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'], 4 ['name' => 'Sue', 'deleted_at' => null], 5]); 6 7$filtered = $collection->where('deleted_at', '!=', null); 8 9$filtered->all();10 11/*12 [13 ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],14 ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],15 ]16*/
whereStrict()
此方法具有与where方法相同的签名;但是,所有值都使用“严格”比较进行比较。
whereBetween()
该whereBetween
方法通过确定指定项目值是否在给定范围内来过滤集合:
1$collection = collect([ 2 ['product' => 'Desk', 'price' => 200], 3 ['product' => 'Chair', 'price' => 80], 4 ['product' => 'Bookcase', 'price' => 150], 5 ['product' => 'Pencil', 'price' => 30], 6 ['product' => 'Door', 'price' => 100], 7]); 8 9$filtered = $collection->whereBetween('price', [100, 200]);10 11$filtered->all();12 13/*14 [15 ['product' => 'Desk', 'price' => 200],16 ['product' => 'Bookcase', 'price' => 150],17 ['product' => 'Door', 'price' => 100],18 ]19*/
whereIn()
该whereIn
方法从集合中删除不具有给定数组中包含的指定项目值的元素:
1$collection = collect([ 2 ['product' => 'Desk', 'price' => 200], 3 ['product' => 'Chair', 'price' => 100], 4 ['product' => 'Bookcase', 'price' => 150], 5 ['product' => 'Door', 'price' => 100], 6]); 7 8$filtered = $collection->whereIn('price', [150, 200]); 9 10$filtered->all();11 12/*13 [14 ['product' => 'Desk', 'price' => 200],15 ['product' => 'Bookcase', 'price' => 150],16 ]17*/
该whereIn
方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将被视为等于相同值的整数。使用whereInStrict方法可以通过“严格”比较进行筛选。
whereInStrict()
此方法具有与whereIn方法相同的签名;但是,所有值都使用“严格”比较进行比较。
whereInstanceOf()
该whereInstanceOf
方法根据给定的类类型过滤集合:
1use App\Models\User; 2use App\Models\Post; 3 4$collection = collect([ 5 new User, 6 new User, 7 new Post, 8]); 9 10$filtered = $collection->whereInstanceOf(User::class);11 12$filtered->all();13 14// [App\Models\User, App\Models\User]
whereNotBetween()
该whereNotBetween
方法通过确定指定项目值是否超出给定范围来过滤集合:
1$collection = collect([ 2 ['product' => 'Desk', 'price' => 200], 3 ['product' => 'Chair', 'price' => 80], 4 ['product' => 'Bookcase', 'price' => 150], 5 ['product' => 'Pencil', 'price' => 30], 6 ['product' => 'Door', 'price' => 100], 7]); 8 9$filtered = $collection->whereNotBetween('price', [100, 200]);10 11$filtered->all();12 13/*14 [15 ['product' => 'Chair', 'price' => 80],16 ['product' => 'Pencil', 'price' => 30],17 ]18*/
whereNotIn()
该whereNotIn
方法从集合中删除具有给定数组中包含的指定项目值的元素:
1$collection = collect([ 2 ['product' => 'Desk', 'price' => 200], 3 ['product' => 'Chair', 'price' => 100], 4 ['product' => 'Bookcase', 'price' => 150], 5 ['product' => 'Door', 'price' => 100], 6]); 7 8$filtered = $collection->whereNotIn('price', [150, 200]); 9 10$filtered->all();11 12/*13 [14 ['product' => 'Chair', 'price' => 100],15 ['product' => 'Door', 'price' => 100],16 ]17*/
该whereNotIn
方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将被视为等于相同值的整数。使用whereNotInStrict方法可以通过“严格”比较进行筛选。
whereNotInStrict()
此方法具有与whereNotIn方法相同的签名;但是,所有值都使用“严格”比较进行比较。
whereNotNull()
该whereNotNull
方法返回集合中不包含给定键的项目null
:
1$collection = collect([ 2 ['name' => 'Desk'], 3 ['name' => null], 4 ['name' => 'Bookcase'], 5]); 6 7$filtered = $collection->whereNotNull('name'); 8 9$filtered->all();10 11/*12 [13 ['name' => 'Desk'],14 ['name' => 'Bookcase'],15 ]16*/
whereNull()
该whereNull
方法返回集合中给定键的项目null
:
1$collection = collect([ 2 ['name' => 'Desk'], 3 ['name' => null], 4 ['name' => 'Bookcase'], 5]); 6 7$filtered = $collection->whereNull('name'); 8 9$filtered->all();10 11/*12 [13 ['name' => null],14 ]15*/
wrap()
静态wrap
方法在适用时将给定值包装在集合中:
1use Illuminate\Support\Collection; 2 3$collection = Collection::wrap('John Doe'); 4 5$collection->all(); 6 7// ['John Doe'] 8 9$collection = Collection::wrap(['John Doe']);10 11$collection->all();12 13// ['John Doe']14 15$collection = Collection::wrap(collect('John Doe'));16 17$collection->all();18 19// ['John Doe']
zip()
该zip
方法将给定数组的值与原始集合中相应索引的值合并在一起:
1$collection = collect(['Chair', 'Desk']);2 3$zipped = $collection->zip([100, 200]);4 5$zipped->all();6 7// [['Chair', 100], ['Desk', 200]]
高阶消息
集合还支持“高阶消息”,即对集合执行常见操作的快捷方式。提供高阶消息的集合方法包括:average、avg、contains、each、every、filter、first、flatMap、groupBy、keyBy、map、max、min、partition、reject、skipUntil、skipWhile、some、sortBy、sortByDesc、sum、takeUntil、takeWhile和unique。
每个高阶消息都可以作为集合实例的动态属性来访问。例如,让我们使用each
高阶消息来调用集合中每个对象的方法:
1use App\Models\User;2 3$users = User::where('votes', '>', 500)->get();4 5$users->each->markAsVip();
同样,我们可以使用sum
高阶消息来收集一组用户的“投票”总数:
1$users = User::where('group', 'Development')->get();2 3return $users->sum->votes;
惰性集合
介绍
在详细了解 Laravel 的惰性集合之前,请花一些时间熟悉PHP 生成器。
为了补充已经很强大的Collection
类,LazyCollection
该类利用 PHP 的生成器,允许您处理非常大的数据集,同时保持较低的内存使用率。
例如,假设你的应用程序需要处理一个数 GB 的日志文件,同时利用 Laravel 的集合方法来解析日志。与其一次性将整个文件读入内存,不如使用惰性集合,在给定时间内只将文件的一小部分保留在内存中:
1use App\Models\LogEntry; 2use Illuminate\Support\LazyCollection; 3 4LazyCollection::make(function () { 5 $handle = fopen('log.txt', 'r'); 6 7 while (($line = fgets($handle)) !== false) { 8 yield $line; 9 }10 11 fclose($handle);12})->chunk(4)->map(function (array $lines) {13 return LogEntry::fromLines($lines);14})->each(function (LogEntry $logEntry) {15 // Process the log entry...16});
或者,假设你需要迭代 10,000 个 Eloquent 模型。使用传统的 Laravel 集合时,所有 10,000 个 Eloquent 模型必须同时加载到内存中:
1use App\Models\User;2 3$users = User::all()->filter(function (User $user) {4 return $user->id > 500;5});
但是,查询构建器的cursor
方法会返回一个LazyCollection
实例。这样,您仍然可以只对数据库运行单个查询,并且每次只能在内存中加载一个 Eloquent 模型。在此示例中,filter
回调直到我们实际对每个用户进行单独迭代时才会执行,从而大幅减少内存使用量:
1use App\Models\User;2 3$users = User::cursor()->filter(function (User $user) {4 return $user->id > 500;5});6 7foreach ($users as $user) {8 echo $user->id;9}
创建惰性集合
要创建惰性集合实例,您应该将 PHP 生成器函数传递给集合的make
方法:
1use Illuminate\Support\LazyCollection; 2 3LazyCollection::make(function () { 4 $handle = fopen('log.txt', 'r'); 5 6 while (($line = fgets($handle)) !== false) { 7 yield $line; 8 } 9 10 fclose($handle);11});
可枚举Contracts
该类中几乎所有可用的方法Collection
在该类中也都可用LazyCollection
。这两个类都实现了Illuminate\Support\Enumerable
契约,该契约定义了以下方法:
all average avg chunk chunkWhile collapse collect combine concat contains containsStrict count countBy crossJoin dd diff diffAssoc diffKeys dump duplicates duplicatesStrict each eachSpread every except filter first firstOrFail firstWhere flatMap flatten flip forPage get groupBy has implode intersect intersectAssoc intersectByKeys isEmpty isNotEmpty join keyBy keys last macro make map mapInto mapSpread mapToGroups mapWithKeys max median merge mergeRecursive min mode nth only pad partition pipe pluck random reduce reject replace replaceRecursive reverse search shuffle skip slice sole some sort sortBy sortByDesc sortKeys sortKeysDesc split sum take tap times toArray toJson union unique uniqueStrict unless unlessEmpty unlessNotEmpty unwrap values when whenEmpty whenNotEmpty where whereStrict whereBetween whereIn whereInStrict whereInstanceOf whereNotBetween whereNotIn whereNotInStrict wrap zip
该类上没有改变集合的方法
(例如shift
、等)。pop
prepend
LazyCollection
惰性收集方法
除了契约中定义的方法之外Enumerable
,该类LazyCollection
还包含以下方法:
takeUntilTimeout()
该takeUntilTimeout
方法返回一个新的惰性集合,该集合将枚举值直到指定时间。在该时间之后,集合将停止枚举:
1$lazyCollection = LazyCollection::times(INF) 2 ->takeUntilTimeout(now()->addMinute()); 3 4$lazyCollection->each(function (int $number) { 5 dump($number); 6 7 sleep(1); 8}); 9 10// 111// 212// ...13// 5814// 59
为了说明此方法的用法,假设有一个应用程序使用游标从数据库提交发票。您可以定义一个计划任务,每 15 分钟运行一次,并且最多只处理 14 分钟的发票:
1use App\Models\Invoice;2use Illuminate\Support\Carbon;3 4Invoice::pending()->cursor()5 ->takeUntilTimeout(6 Carbon::createFromTimestamp(LARAVEL_START)->add(14, 'minutes')7 )8 ->each(fn (Invoice $invoice) => $invoice->submit());
tapEach()
虽然该each
方法会立即为集合中的每个项目调用给定的回调,但该tapEach
方法仅在将项目逐个从列表中拉出时才调用给定的回调:
1// Nothing has been dumped so far... 2$lazyCollection = LazyCollection::times(INF)->tapEach(function (int $value) { 3 dump($value); 4}); 5 6// Three items are dumped... 7$array = $lazyCollection->take(3)->all(); 8 9// 110// 211// 3
throttle()
该throttle
方法将限制惰性集合,使每个值在指定的秒数后返回。此方法在与外部 API 交互且对传入请求进行速率限制的情况下尤其有用:
1use App\Models\User;2 3User::where('vip', true)4 ->cursor()5 ->throttle(seconds: 1)6 ->each(function (User $user) {7 // Call external API...8 });
remember()
该remember
方法返回一个新的惰性集合,它将记住任何已经枚举的值,并且不会在后续集合枚举中再次检索它们:
1// No query has been executed yet... 2$users = User::cursor()->remember(); 3 4// The query is executed... 5// The first 5 users are hydrated from the database... 6$users->take(5)->all(); 7 8// First 5 users come from the collection's cache... 9// The rest are hydrated from the database...10$users->take(20)->all();