集合
介绍
Illuminate\Support\Collection
类提供了一个流畅、方便的包装器,用于处理数据数组。例如,请查看以下代码。我们将使用 collect
辅助函数从数组创建一个新的集合实例,对每个元素运行 strtoupper
函数,然后移除所有空元素:
$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
return strtoupper($name);
})
->reject(function ($name) {
return empty($name);
});
正如你所看到的,Collection
类允许你链式调用其方法,以流畅地映射和减少底层数组。一般来说,集合是不可变的,这意味着每个 Collection
方法都会返回一个全新的 Collection
实例。
创建集合
如上所述,collect
辅助函数为给定数组返回一个新的 Illuminate\Support\Collection
实例。因此,创建一个集合就像这样简单:
$collection = collect([1, 2, 3]);
Eloquent 查询的结果总是以 Collection
实例返回。
可用方法
在本文档的其余部分,我们将讨论 Collection
类上可用的每个方法。请记住,所有这些方法都可以链式调用,以流畅地操作底层数组。此外,几乎每个方法都会返回一个新的 Collection
实例,以便在必要时保留集合的原始副本:
allaverageavgchunkcollapsecombinecontainscontainsStrictcountdiffdiffKeyseacheveryexceptfilterfirstflatMapflattenflipforgetforPagegetgroupByhasimplodeintersectisEmptyisNotEmptykeyBykeyslastmapmapWithKeysmaxmedianmergeminmodeonlypartitionpipepluckpopprependpullpushputrandomreducerejectreversesearchshiftshuffleslicesortsortBysortByDescsplicesplitsumtaketoArraytoJsontransformunionuniqueuniqueStrictvalueswherewhereStrictwhereInwhereInStrictzip
方法列表
all()
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();
// 2
chunk()
chunk
方法将集合分成多个较小的集合,每个集合的大小由给定的大小决定:
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[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>
@endforeach
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]
combine()
combine
方法将集合的键与另一个数组或集合的值组合:
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]
contains()
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');
// false
最后,你还可以将回调传递给 contains
方法以执行你自己的真值测试:
$collection = collect([1, 2, 3, 4, 5]);
$collection->contains(function ($value, $key) {
return $value > 5;
});
// false
contains
方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将被视为与相同值的整数相等。使用 containsStrict
方法以“严格”比较进行过滤。
containsStrict()
此方法与 contains
方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。
count()
count
方法返回集合中的项目总数:
$collection = collect([1, 2, 3, 4]);
$collection->count();
// 4
diff()
diff
方法根据其值将集合与另一个集合或普通 PHP array
进行比较。此方法将返回原始集合中不存在于给定集合中的值:
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]
diffKeys()
diffKeys
方法根据其键将集合与另一个集合或普通 PHP array
进行比较。此方法将返回原始集合中不存在于给定集合中的键/值对:
$collection = collect([
'one' => 10,
'two' => 20,
'three' => 30,
'four' => 40,
'five' => 50,
]);
$diff = $collection->diffKeys([
'two' => 2,
'four' => 4,
'six' => 6,
'eight' => 8,
]);
$diff->all();
// ['one' => 10, 'three' => 30, 'five' => 50]
each()
each
方法遍历集合中的项目并将每个项目传递给回调:
$collection = $collection->each(function ($item, $key) {
//
});
如果你想停止遍历项目,可以从回调中返回 false
:
$collection = $collection->each(function ($item, $key) {
if (/* some condition */) {
return false;
}
});
every()
every
方法创建一个由每 n 个元素组成的新集合:
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->every(4);
// ['a', 'e']
你可以选择性地传递一个偏移量作为第二个参数:
$collection->every(4, 1);
// ['b', 'f']
except()
except
方法返回集合中除指定键之外的所有项目:
$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);
$filtered = $collection->except(['price', 'discount']);
$filtered->all();
// ['product_id' => 1]
有关 except
的反义词,请参见 only 方法。
filter()
filter
方法使用给定的回调过滤集合,仅保留通过给定真值测试的项目:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $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 ($value, $key) {
return $value > 2;
});
// 3
你还可以在没有参数的情况下调用 first
方法以获取集合中的第一个元素。如果集合为空,则返回 null
:
collect([1, 2, 3, 4])->first();
// 1
flatMap()
flatMap
方法遍历集合并将每个值传递给给定的回调。回调可以自由修改项目并返回它,从而形成一个新的修改项目集合。然后,数组被平展一级:
$collection = collect([
['name' => 'Sally'],
['school' => 'Arkansas'],
['age' => 28]
]);
$flattened = $collection->flatMap(function ($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'];
你可以选择性地传递一个“深度”参数:
$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'],
]
*/
在此示例中,如果不提供深度调用 flatten
,则还会平展嵌套数组,结果为 ['iPhone 6S', 'Apple', 'Galaxy S7', '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']
与大多数其他集合方法不同,forget
不返回一个新的修改集合;它修改调用它的集合。
forPage()
forPage
方法返回一个新集合,其中包含将在给定页码上显示的项目。该方法接受页码作为第一个参数,显示每页项目数作为第二个参数:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);
$chunk->all();
// [4, 5, 6]
get()
get
方法返回给定键的项目。如果键不存在,则返回 null
:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('name');
// taylor
你可以选择性地传递一个默认值作为第二个参数:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('foo', 'default-value');
// default-value
你甚至可以将回调作为默认值传递。如果指定的键不存在,将返回回调的结果:
$collection->get('email', function () {
return 'default-value';
});
// default-value
groupBy()
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->toArray();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
除了传递字符串 key
,你还可以传递回调。回调应返回你希望分组的值:
$grouped = $collection->groupBy(function ($item, $key) {
return substr($item['account_id'], -3);
});
$grouped->toArray();
/*
[
'x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
has()
has
方法确定集合中是否存在给定键:
$collection = collect(['account_id' => 1, 'product' => 'Desk']);
$collection->has('product');
// true
implode()
implode
方法连接集合中的项目。其参数取决于集合中项目的类型。如果集合包含数组或对象,你应该传递你希望连接的属性的键,以及你希望在值之间放置的“胶水”字符串:
$collection = collect([
['account_id' => 1, 'product' => 'Desk'],
['account_id' => 2, 'product' => 'Chair'],
]);
$collection->implode('product', ', ');
// Desk, Chair
如果集合包含简单的字符串或数值,只需将“胶水”作为方法的唯一参数传递:
collect([1, 2, 3, 4, 5])->implode('-');
// '1-2-3-4-5'
intersect()
intersect
方法从原始集合中移除任何不在给定 array
或集合中的值。结果集合将保留原始集合的键:
$collection = collect(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']
isEmpty()
isEmpty
方法返回 true
如果集合为空;否则返回 false
:
collect([])->isEmpty();
// true
isNotEmpty()
isNotEmpty
方法返回 true
如果集合不为空;否则返回 false
:
collect([])->isNotEmpty();
// false
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 ($item) {
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 ($value, $key) {
return $value < 3;
});
// 2
你还可以在没有参数的情况下调用 last
方法以获取集合中的最后一个元素。如果集合为空,则返回 null
:
collect([1, 2, 3, 4])->last();
// 4
map()
map
方法遍历集合并将每个值传递给给定的回调。回调可以自由修改项目并返回它,从而形成一个新的修改项目集合:
$collection = collect([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]
像大多数其他集合方法一样,map
返回一个新的集合实例;它不会修改调用它的集合。如果你想转换原始集合,请使用 transform
方法。
mapWithKeys()
mapWithKeys
方法遍历集合并将每个值传递给给定的回调。回调应返回一个包含单个键/值对的关联数组:
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john@example.com'
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane@example.com'
]
]);
$keyed = $collection->mapWithKeys(function ($item) {
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();
// 5
median()
median
方法返回给定键的中位数:
$median = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');
// 15
$median = collect([1, 1, 2, 4])->median();
// 1.5
merge()
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']
min()
min
方法返回给定键的最小值:
$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
// 10
$min = collect([1, 2, 3, 4, 5])->min();
// 1
mode()
mode
方法返回给定键的众数:
$mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');
// [10]
$mode = collect([1, 1, 2, 4])->mode();
// [1]
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 方法。
partition()
partition
方法可以与 PHP 的 list
函数结合使用,以将通过给定真值测试的元素与未通过的元素分开:
$collection = collect([1, 2, 3, 4, 5, 6]);
list($underThree, $aboveThree) = $collection->partition(function ($i) {
return $i < 3;
});
pipe()
pipe
方法将集合传递给给定的回调并返回结果:
$collection = collect([1, 2, 3]);
$piped = $collection->pipe(function ($collection) {
return $collection->sum();
});
// 6
pluck()
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']
pop()
pop
方法移除并返回集合中的最后一个项目:
$collection = collect([1, 2, 3, 4, 5]);
$collection->pop();
// 5
$collection->all();
// [1, 2, 3, 4]
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
以指定你希望随机检索多少个项目。如果该整数大于 1
,则返回一个项目集合:
$random = $collection->random(3);
$random->all();
// [2, 4, 5] - (随机检索)
reduce()
reduce
方法将集合减少为单个值,将每次迭代的结果传递给后续迭代:
$collection = collect([1, 2, 3]);
$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
});
// 6
第一次迭代中 $carry
的值为 null
;然而,你可以通过传递第二个参数给 reduce
来指定其初始值:
$collection->reduce(function ($carry, $item) {
return $carry + $item;
}, 4);
// 10
reject()
reject
方法使用给定的回调过滤集合。回调应返回 true
如果项目应从结果集合中移除:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->reject(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// [1, 2]
有关 reject
方法的反义词,请参见 filter
方法。
reverse()
reverse
方法反转集合中项目的顺序:
$collection = collect([1, 2, 3, 4, 5]);
$reversed = $collection->reverse();
$reversed->all();
// [5, 4, 3, 2, 1]
search()
search
方法在集合中搜索给定值并返回其键(如果找到)。如果未找到项目,则返回 false
。
$collection = collect([2, 4, 6, 8]);
$collection->search(4);
// 1
搜索是使用“宽松”比较进行的,这意味着具有整数值的字符串将被视为与相同值的整数相等。要使用“严格”比较,请将 true
作为第二个参数传递给方法:
$collection->search('4', true);
// false
或者,你可以传入自己的回调以搜索第一个通过你的真值测试的项目:
$collection->search(function ($item, $key) {
return $item > 5;
});
// 2
shift()
shift
方法从集合中移除并返回第一个项目:
$collection = collect([1, 2, 3, 4, 5]);
$collection->shift();
// 1
$collection->all();
// [2, 3, 4, 5]
shuffle()
shuffle
方法随机打乱集合中的项目:
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] - (随机生成)
slice()
slice
方法返回从给定索引开始的集合切片:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4);
$slice->all();
// [5, 6, 7, 8, 9, 10]
如果你想限制返回切片的大小,请将所需的大小作为方法的第二个参数传递:
$slice = $collection->slice(4, 2);
$slice->all();
// [5, 6]
返回的切片将默认保留键。如果你不希望保留原始键,可以使用 values
方法重新索引它们。
sort()
sort
方法对集合进行排序。排序后的集合保留原始数组键,因此在此示例中我们将使用 values
方法将键重置为连续编号的索引:
$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]
如果你的排序需求更高级,可以将回调传递给 sort
以使用你自己的算法。请参阅 PHP 文档中的 usort
,这是集合的 sort
方法在底层调用的。
如果你需要对嵌套数组或对象的集合进行排序,请参阅 sortBy
和 sortByDesc
方法。
sortBy()
sortBy
方法按给定键对集合进行排序。排序后的集合保留原始数组键,因此在此示例中我们将使用 values
方法将键重置为连续编号的索引:
$collection = collect([
['name' => 'Desk', 'price' => 200],
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
]);
$sorted = $collection->sortBy('price');
$sorted->values()->all();
/*
[
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
['name' => 'Desk', 'price' => 200],
]
*/
你还可以传递自己的回调来确定如何对集合值进行排序:
$collection = collect([
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$sorted = $collection->sortBy(function ($product, $key) {
return count($product['colors']);
});
$sorted->values()->all();
/*
[
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]
*/
sortByDesc()
此方法与 sortBy
方法具有相同的签名,但会以相反的顺序对集合进行排序。
splice()
splice
方法移除并返回从指定索引开始的项目切片:
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2);
$chunk->all();
// [3, 4, 5]
$collection->all();
// [1, 2]
你可以传递第二个参数来限制结果切片的大小:
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 4, 5]
此外,你可以传递第三个参数,其中包含要替换从集合中移除的项目的新项目:
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1, [10, 11]);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 10, 11, 4, 5]
split()
split
方法将集合分成给定数量的组:
$collection = collect([1, 2, 3, 4, 5]);
$groups = $collection->split(3);
$groups->toArray();
// [[1, 2], [3, 4], [5]]
sum()
sum
方法返回集合中所有项目的总和:
collect([1, 2, 3, 4, 5])->sum();
// 15
如果集合包含嵌套数组或对象,你应该传递一个键来确定要求和的值:
$collection = collect([
['name' => 'JavaScript: The Good Parts', 'pages' => 176],
['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);
$collection->sum('pages');
// 1272
此外,你可以传递自己的回调来确定集合中要求和的值:
$collection = collect([
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$collection->sum(function ($product) {
return count($product['colors']);
});
// 6
take()
take
方法返回一个包含指定数量项目的新集合:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]
你还可以传递一个负整数以从集合的末尾获取指定数量的项目:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(-2);
$chunk->all();
// [4, 5]
toArray()
toArray
方法将集合转换为普通 PHP array
。如果集合的值是 Eloquent 模型,模型也将被转换为数组:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/
toArray
还将集合的所有嵌套对象转换为数组。如果你想获取原始底层数组,请使用 all
方法。
toJson()
toJson
方法将集合转换为 JSON 序列化字符串:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toJson();
// '{"name":"Desk", "price":200}'
transform()
transform
方法遍历集合并使用集合中的每个项目调用给定的回调。集合中的项目将被回调返回的值替换:
$collection = collect([1, 2, 3, 4, 5]);
$collection->transform(function ($item, $key) {
return $item * 2;
});
$collection->all();
// [2, 4, 6, 8, 10]
与大多数其他集合方法不同,transform
修改集合本身。如果你希望创建一个新集合,请使用 map
方法。
union()
union
方法将给定的数组添加到集合中。如果给定数组包含已经在原始集合中的键,则原始集合的值将被优先:
$collection = collect([1 => ['a'], 2 => ['b']]);
$union = $collection->union([3 => ['c'], 1 => ['b']]);
$union->all();
// [1 => ['a'], 2 => ['b'], 3 => ['c']]
unique()
unique
方法返回集合中所有唯一的项目。返回的集合保留原始数组键,因此在此示例中我们将使用 values
方法将键重置为连续编号的索引:
$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
在处理嵌套数组或对象时,你可以指定用于确定唯一性的键:
$collection = collect([
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);
$unique = $collection->unique('brand');
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
]
*/
你还可以传递自己的回调来确定项目的唯一性:
$unique = $collection->unique(function ($item) {
return $item['brand'].$item['type'];
});
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]
*/
unique
方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将被视为与相同值的整数相等。使用 uniqueStrict
方法以“严格”比较进行过滤。
uniqueStrict()
此方法与 unique
方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。
values()
values
方法返回一个新集合,其中的键重置为连续整数:
$collection = collect([
10 => ['product' => 'Desk', 'price' => 200],
11 => ['product' => 'Desk', 'price' => 200]
]);
$values = $collection->values();
$values->all();
/*
[
0 => ['product' => 'Desk', 'price' => 200],
1 => ['product' => 'Desk', 'price' => 200],
]
*/
where()
where
方法通过给定的键/值对过滤集合:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->where('price', 100);
$filtered->all();
/*
[
['product' => 'Chair', 'price' => 100],
['product' => 'Door', 'price' => 100],
]
*/
where
方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将被视为与相同值的整数相等。使用 whereStrict
方法以“严格”比较进行过滤。
whereStrict()
此方法与 where
方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。
whereIn()
whereIn
方法通过给定数组中包含的键/值对过滤集合:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereIn('price', [150, 200]);
$filtered->all();
/*
[
['product' => 'Bookcase', 'price' => 150],
['product' => 'Desk', 'price' => 200],
]
*/
whereIn
方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将被视为与相同值的整数相等。使用 whereInStrict
方法以“严格”比较进行过滤。
whereInStrict()
此方法与 whereIn
方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。
zip()
zip
方法将给定数组的值与原始集合的值按对应索引合并在一起:
$collection = collect(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]