集合
簡(jiǎn)介
Illuminate\Support\Collection
類提供了對(duì)數(shù)組數(shù)據(jù)流利操作的封裝乏悄。比如秧了,看下面的延時(shí)代碼倦蚪。我們會(huì)使用 collect
幫助方法從一個(gè)數(shù)組中創(chuàng)建一個(gè)新的集合實(shí)例侈离,然后運(yùn)行 strtoupper
方法轉(zhuǎn)為大寫再剔除集合中的空元素:
$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
return strtoupper($name);
})
->reject(function ($name) {
return empty($name);
});
就如你所看到的蹄葱,Collection
類允許你鏈?zhǔn)降恼{(diào)用它的方法峦筒,就是這樣提供了一種流利的映射的執(zhí)行能力的同時(shí)縮小了底層的數(shù)組究西。通常情況下,所有的 Collection
方法都會(huì)返回一個(gè)全新的 Collection
實(shí)例物喷。
創(chuàng)建集合
就如上面的代碼卤材,collect
幫助方法會(huì)根據(jù)給定的數(shù)組返回一個(gè)新的 Illuminate\Support\Collection
實(shí)例遮斥。所以,創(chuàng)建一個(gè)集合是非常的簡(jiǎn)單:
$collection = collect([1, 2, 3]);
默認(rèn)的扇丛,Eloquent 模型集合總是返回 Collection
的實(shí)例术吗。事實(shí)上,你可以在你的應(yīng)用中任意位置使用 Collection
類帆精。
可用的方法
在文檔的余下部分较屿,我們將探討 Collection
類中所有可用的方法。你應(yīng)該記住卓练,所有的這些方法都可以鏈?zhǔn)秸{(diào)用來流利的操作底層的數(shù)組隘蝎。另外,幾乎每一個(gè)方法都會(huì)返回一個(gè)新的 Collection
實(shí)例襟企,這允許你可以在必要時(shí)保存原始的集合嘱么。
方法名單
all()
all
方法會(huì)簡(jiǎn)單的返回集合中所包含的底層數(shù)組:
collect([1, 2, 3])->all();
// [1, 2, 3]
avg()
avg
方法會(huì)返回集合中所有項(xiàng)的平均值:
collect([1, 2, 3, 4, 5])->avg();
// 3
如果集合中包含的是嵌套的數(shù)組或者對(duì)象,你應(yīng)該傳遞 key 來表明所需要計(jì)算的值的平均值:
$collection = collect([
['name' => 'JavaScript: The Good Parts', 'pages' => 176],
['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);
$collection->avg('pages');
// 636
chunk()
chunk
方法會(huì)根據(jù)給定的大小來將集合分割成多個(gè)小的集合:
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
該方法在視圖中使用類似于 Bootstrap 的網(wǎng)格系統(tǒng)時(shí)特別有用顽悼。想象一下你有一個(gè)關(guān)于 Eloquent 模型的集合想要在網(wǎng)格中顯示:
@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
方法會(huì)將集合中的數(shù)組從多維坍塌到一維:
$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
方法會(huì)將一個(gè)集合中的 keys 和另外一個(gè)集合或數(shù)組中的 values 相結(jié)合:
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]
contains()
contains
方法來判斷集合中是否含有給定的項(xiàng):
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->contains('Desk');
// true
$collection->contains('New York');
// false
你也可以傳遞鍵值對(duì)到 contains
方法曼振,這將會(huì)用來判斷集合中是否含有給定的鍵值對(duì)項(xiàng):
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->contains('product', 'Bookcase');
// false
最后,你也可以傳遞一個(gè)匿名函數(shù)到 contains
方法來提供自己的真值判斷邏輯:
$collection = collect([1, 2, 3, 4, 5]);
$collection->contains(function ($key, $value) {
return $value > 5;
});
// false
count()
count
方法會(huì)返回集合中項(xiàng)目的總數(shù):
$collection = collect([1, 2, 3, 4]);
$collection->count();
// 4
diff()
diff
方法用來比較集合中存在而其他集合或者原生 PHP 的數(shù)組不存在的值:
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]
diffKeys()
diffKeys
方法用來比較集合中存在而其他集合或原生 PHP 數(shù)組不存在的鍵:
$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
方法會(huì)迭代集合中的每一項(xiàng)蔚龙,并將該項(xiàng)傳遞給所給定的回調(diào):
$collection = $collection->each(function ($item, $key) {
//
});
在回調(diào)中返回 `false` 將會(huì)中斷迭代:
```php
$collection = $collection->each(function ($item, $key) {
if (/* some condition */) {
return false;
}
});
every()
every
方法會(huì)創(chuàng)建一個(gè)由每第 N 個(gè)元素(包含起始位)所組成的集合:
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->every(4);
// ['a', 'e']
你可以傳遞第二個(gè)參數(shù)來設(shè)置位移:
$collection->every(4, 1);
// ['b', 'f']
except()
except
方法返回集合中的項(xiàng)冰评,并在項(xiàng)目中剔除選定的鍵:
$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
$filtered = $collection->except(['price', 'discount']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']
filter()
filter
方法會(huì)根據(jù)給定的回調(diào)的迭代結(jié)果進(jìn)行過濾,如果回調(diào)返回的是真值木羹,該項(xiàng)將會(huì)被保留:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// [3, 4]
rejct
方法與 filter
方法相反集索。
first()
first
方法會(huì)返回集合中第一個(gè)回調(diào)返回真值的項(xiàng):
collect([1, 2, 3, 4])->first(function ($key, $value) {
return $value > 2;
});
// 3
你也可以調(diào)用無參數(shù)的 first
方法,該方法會(huì)返回集合中的第一個(gè)元素汇跨。如果集合是空的,則會(huì)返回 null
:
collect([1, 2, 3, 4])->first();
// 1
flatMap()
flatMap
方法會(huì)迭代處理所有元素妆距,并將處理后的集合進(jìn)行扁平化處理(從多維降為一維):
$collection = collect(
['name' => 'Sally'],
['school' => 'Arkansas'],
['age' => 28]
);
$flattened = $collection->flatMap(function ($values) {
return strtoupper($values);
});
$flattened->all();
// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => 28];
flatten()
flatten
方法將多規(guī)格的集合轉(zhuǎn)換為單一格式的集合:
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['taylor', 'php', 'javascript'];
你也可以傳遞一個(gè)“深度”參數(shù)到方法:
$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'],
]
*/
這里穷遂,調(diào)用不提供深度的 flatten
方法也會(huì)扁平化數(shù)組,這將導(dǎo)致返回 ['iPhone 6S', 'Apple', 'GalaxyS7', 'Samsung']
娱据。提供深度可以使你限制拉平嵌套數(shù)組的層級(jí)蚪黑。
flip()
flip
方法將會(huì)反轉(zhuǎn)鍵值對(duì):
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$flipped = $collection->flip();
$flipped->all();
// ['taylor' => 'name', 'laravel' => 'framework']
forget()
forget
方法根據(jù)所提供的鍵剔除集合中相應(yīng)的項(xiàng):
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$collection->forget('name');
$collection->all();
// ['framework' => 'laravel']
注意: 不像其他的集合方法,
forget
方法不會(huì)返回一個(gè)新的修改后的集合中剩,它會(huì)直接修改當(dāng)前的集合忌穿。
forPage()
forPage
方法將返回給定當(dāng)前頁所包含的項(xiàng)的集合:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);
$chunk->all();
// [4, 5, 6]
該方法需要傳遞當(dāng)前頁的數(shù)值及每頁所包含的數(shù)目。
get()
get
方法將根據(jù)給定的鍵從集合中返回項(xiàng)结啼,如果給定鍵不存在掠剑,則返回 null
:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('name');
// taylor
你可以傳遞第二個(gè)參數(shù)來作為默認(rèn)值:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('foo', 'default-value');
// default-value
你也可以傳遞一個(gè)回調(diào)作為默認(rèn)值〗祭ⅲ回調(diào)的結(jié)果將會(huì)被作為未找到鍵時(shí)的默認(rèn)值:
$collection->get('email', function () {
return 'default-value';
});
// default-value
groupBy()
groupBy
方法將會(huì)根據(jù)給定的鍵將集合進(jìn)行分組:
$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', 'prodcut' => 'Desk'],
],
]
*/
除了傳遞一個(gè)字符串 key
之外朴译,你也可以傳遞一個(gè)回調(diào)函數(shù)井佑。回調(diào)函數(shù)應(yīng)該返回你所期望進(jìn)行分組的鍵的值:
$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('email');
// false
implode()
implode
方法會(huì)將集合中的項(xiàng)連接成字符串眠寿。其參數(shù)取決于集合中的項(xiàng)目類型躬翁。
如果集合中包含的是鍵值對(duì)數(shù)組或?qū)ο螅憔蛻?yīng)該傳遞一個(gè)鍵到方法來表明你想要連接的值盯拱,然后緊跟著一個(gè)膠連字符串參數(shù):
$collection = collect([
['account_id' => 1, 'product' => 'Desk'],
['account_id' => 2, 'product' => 'Chair'],
]);
$collection->implode('product', ', ');
// Desk, Chair
如果集合只是包含了簡(jiǎn)單的字符串或者數(shù)組類型的值盒发,你可以直接傳遞膠連字符串參數(shù)到方法:
collect([1, 2, 3, 4, 5])->implode('-');
// '1-2-3-4-5'
intersect()
intersect
方法返回給定數(shù)組與集合的交集:
$collection = collect(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']
就如你所看到的,結(jié)果集合將保留原始集合的鍵狡逢。
isEmpty()
isEmpty
方法用來判斷集合是否為空宁舰,如果集合為空,則返回 true
甚侣,否則返回 false
:
collect([])->isEmpty();
// true
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'],
]
*/
如果多個(gè)項(xiàng)目含有相同的鍵明吩,那么只有最后一個(gè)項(xiàng)目會(huì)出現(xiàn)在新的集合中。
你也可以傳遞你自己的回調(diào)來返回集合鍵的值:
$keyed = $collection->keyBy(function ($item) {
return strtoupper($imte['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
方法返回回調(diào)中最后一個(gè)返回真值的項(xiàng):
collect([1, 2, 3, 4])->last(function ($key, $value) {
return $value < 3;
});
// 2
你也可以調(diào)用無參數(shù)的 last
方法殷费,它將返回集合中最后一個(gè)元素印荔,如果集合為空,則返回 null
:
collect([1, 2, 3, 4])->last();
// 4
map()
map
方法會(huì)使用給定的回調(diào)來進(jìn)行迭代集合中的所有項(xiàng)详羡,在回調(diào)函數(shù)中可以自由的修改該項(xiàng)并進(jìn)行返回仍律,這樣新的集合將包含修改后的值:
$collection = collect([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]
注意:就像其他的集合方法一樣,
map
返回一個(gè)新的集合實(shí)例实柠。它并不會(huì)突變?cè)纤H绻阆胍谠屑现羞M(jìn)行改變,你應(yīng)該使用transform
方法窒盐。
max()
max
方法返回給定鍵中最大的值:
$max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
// 20
$max = collect([1, 2, 3, 4, 5])->max();
// 5
merge()
merge
方法會(huì)合并給定的數(shù)組到集合草则。數(shù)組中的值將會(huì)覆蓋集合中相同鍵的值:
$colletion = collect(['product_id' => 1, 'name' => 'Desk']);
$merged = $collection->merge(['price' => 100, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]
如果給定的數(shù)組的鍵是數(shù)值,則它的值將會(huì)被追加在集合的末尾:
$collection = collect(['Desk', 'Chair']);
$merged = $collection->merge(['Bookcase', 'Door']);
$merged->all();
// ['Desk', 'Chair', 'Bookcase', 'Door']
min()
min
方法會(huì)返回集合中給定鍵的最小值:
$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
// 10
$min = collect([1, 2, 3, 4, 5])->min();
// 1
only()
only
方法返回集合中的項(xiàng)蟹漓,并修改項(xiàng)目中的鍵值只包含選定的鍵:
$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
$filtered = $collection->only(['product_id', 'name']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']
pluck()
pluck
方法將根據(jù)給定的鍵檢索集合中所有項(xiàng)的值:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
你也可以指定將結(jié)果如何鍵化:
$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
pop()
pop
方法將從集合中剔除最后一個(gè)元素:
$collection = collect([1, 2, 3, 4, 5]);
$collection->pop();
// 5
$collection->all();
// [1, 2, 3, 4]
prepend()
prepend
方法將在集合的起始端添加項(xiàng)目:
$collection = collect([1, 2, 3, 4, 5]);
$collection->prepend(0);
$collection->all();
// [0, 1, 2, 3, 4, 5]
你也可以傳遞第二個(gè)參數(shù)作為前置項(xiàng)目的鍵:
$collection = collect(['one' => 1, 'two' => 2]);
$collection->prepend(0, 'zero');
$collection->all();
// ['zero' => 0, 'one' => 1, 'two' => 2]
pull()
pull
方法從集合中返回給定鍵的同時(shí)將其從集合中剔除:
$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
方法在集合中設(shè)置給定的鍵和值:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->put('price', 100);
$collection->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
random()
random
方法隨機(jī)的從集合中返回元素:
$collection = collect([1, 2, 3, 4, 5]);
$collection->random();
// 4 - (ertrieved randomly)
你也可以傳遞一個(gè)整型值到 random
炕横。如果整型值大于 1
。則相應(yīng)個(gè)數(shù)的隨機(jī)項(xiàng)將會(huì)被返回:
$random = $collection->random(3);
$random->all();
// [2, 4, 5] - (retrieved randomly)
reduce()
reduce
方法將會(huì)縮小集合收集單個(gè)值葡粒。它會(huì)通過迭代的方式將其值傳遞給隨后的迭代器:
$collection = collect([1, 2, 3]);
$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
});
// 6
上面的 $carry
在第一個(gè)迭代器中將會(huì)是 null
份殿;你也可以指定一個(gè)起始值到第二個(gè)參數(shù):
$collection->reduce(function ($carry, $item) {
return $carry + $item;
}, 4);
// 10
reject()
reject
方法使用給定的回調(diào)從集合中返回過濾的值。你需要在回調(diào)中返回 true
來讓其從結(jié)果中移除:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection=>reject(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// [1, 2]
reverse()
reverse
方法會(huì)逆序排列集合中的項(xiàng)目:
$collection = collect([1, 2, 3, 4, 5]);
$reversed = $collection->reverse();
$reversed->all();
// [5, 4, 3, 2, 1]
search()
search
方法根據(jù)給定的值搜索集合中的項(xiàng)嗽交,如果找到則返回該項(xiàng)的鍵卿嘲,如果未找到則返回 false
:
$collection = collect([2, 4, 6, 8]);
$collection->search(4);
// 1
搜索使用的是疏松的比較,如果需要進(jìn)行嚴(yán)格比較夫壁,你應(yīng)該傳遞 true
作為第二個(gè)參數(shù):
$collection->search('4', true);
// false
另外拾枣,你也可以傳遞一個(gè)回調(diào)作為搜索的結(jié)果判斷依據(jù),在回調(diào)中首個(gè)返回真值的項(xiàng)目將會(huì)被檢索到:
$collection->search(function ($item, $key) {
return $item > 5;
});
// 2
shift()
shift
方法會(huì)從集合中返回首個(gè)元素的同時(shí)從集合中剔除:
$collection = collect([1, 2, 3, 4, 5]);
$collection->shift();
// 1
$collection->all();
// [2, 3, 4, 5]
shuffle()
shuffle
方法隨機(jī)打亂集合中項(xiàng)目的順序:
$collect = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] // (generated randomly)
slice()
slice
方法根據(jù)給定的索引返回集合中的一小片:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4);
$slice->all();
// [5, 6, 7, 8, 9, 10]
如果你想要限制返回的切片的大小盒让,你可以傳遞期望的大小到第二個(gè)參數(shù):
$slice = $collection->slice(4, 2);
$slice->all();
// [5, 6]
返回的切片將會(huì)有一個(gè)新的數(shù)字索引鍵放前。如果你想要保留原數(shù)組的鍵忿磅,你需要傳遞 true
到第三個(gè)參數(shù)。
sort()
sort
方法將對(duì)集合進(jìn)行排序:
$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3 ,4 ,5]
被排序的集合會(huì)保留原始的數(shù)組鍵凭语。上面的例子中我們使用了 values
方法來重置了鍵到連續(xù)的數(shù)字索引葱她。
對(duì)于嵌套的數(shù)組或者對(duì)象的排序,請(qǐng)參照 sortBy
和 sortByDesc
方法似扔。
如果你的排序需要更多的邏輯支持吨些,你可以傳遞一個(gè)回調(diào)到 sort
方法。你可以參考 PHP 文檔的 usort, 集合的 sort
方法就是在基于該方法的炒辉。
sortBy()
sortBy
方法根據(jù)給定的鍵進(jìn)行集合排序:
$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],
]
*/
被排序的集合會(huì)保留原始的數(shù)組鍵豪墅。上面的例子中我們使用了 values
方法來重置了鍵到連續(xù)的數(shù)字索引。
你也可以傳遞你自己的回調(diào)作為排序的邏輯依靠:
$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
方法有相同的運(yùn)作方式黔寇,但是它是以集合中相反的順序進(jìn)行排序偶器。
splice()
splice
方法根據(jù)指定的索引來從集合中剔除一片:
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2);
$chunk->all();
// [3, 4, 5]
$collection->all();
// [1, 2]
你也可以傳遞第二個(gè)參數(shù)到方法來限制切片的大小:
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 4, 5]
另外缝裤,你可以傳遞第三個(gè)參數(shù)來作為從原集合中剔除元素的補(bǔ)償:
$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]
sum()
sum
方法返回集合中所有項(xiàng)的和:
collect([1, 2, 3, 4, 5])->sum();
// 15
如果集合中包含的是嵌套的數(shù)組或者對(duì)象屏轰。你可以傳遞鍵來決定需要求和的值:
$collection = collect([
['name' => 'JavaScript: The Good Parts', 'pages' => 176],
['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);
$collection->sum('pages');
// 1272
另外,你也可以傳遞一個(gè)回調(diào)來決定你所需要進(jìn)行求和的值:
$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'))
});
take()
take
方法從集合中返回給定數(shù)值的項(xiàng)目:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]
你也可以傳遞一個(gè)負(fù)值到方法憋飞,它將從集合的結(jié)尾開始返回:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(-2);
$chunk->all();
// [4, 5]
toArray()
toArray
方法會(huì)將集合退化為原生的 PHP 數(shù)組霎苗。如果集合的值列是 Eloquent 模型。模型也會(huì)被轉(zhuǎn)化為數(shù)組:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/
注意:
toArray
也會(huì)轉(zhuǎn)化所有的嵌套的對(duì)象到數(shù)組榛做。如果你希望得到底層的原始數(shù)組唁盏,你可以使用all
方法。
toJson()
toJson
方法轉(zhuǎn)化集合到 JSON:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toJson();
// '{"name":"Desk","price":200}'
transform()
transform
通過一個(gè)回調(diào)函數(shù)迭代處理集合中的項(xiàng)目检眯。集合中的項(xiàng)目會(huì)在被迭代的結(jié)果所替換:
$collection = collect([1, 2, 3, 4, 5]);
$collection->transform(function ($item, $key) {
return $item * 2;
});
$collection->all();
// [2, 4, 6, 8, 10]
注意:不像其他的集合方法厘擂,
transform
會(huì)修改原始的集合自身。如果你希望創(chuàng)建一個(gè)新的集合來替代锰瘸,請(qǐng)使用map
方法驴党。
union()
union
方法添加給定的數(shù)組到集合。如果給定的數(shù)組中包含的鍵在集合中已經(jīng)存在获茬,那么集合中的鍵將會(huì)被保留:
$collection = collect([1 => ['a'], 2 => ['b']]);
$union = $collection->union([3 => ['c'], 1 => ['b']]);
$union->all();
// [1 => ['a'], 2 => ['b'], 3 => ['c']]
unique()
unique
方法將返回所有在集合中具有獨(dú)特性(去重)的項(xiàng)目:
$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
返回的集合中保留了原始的數(shù)組鍵,上面的例子用使用了 values
方法來重置鍵到連續(xù)的數(shù)組索引倔既。
當(dāng)對(duì)嵌套的數(shù)組或者對(duì)象進(jìn)行運(yùn)算時(shí)恕曲,你應(yīng)該制定一個(gè)鍵來進(jìn)行唯一性的判定:
$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']
]
*/
你也可以傳遞自己的回調(diào)到方法來進(jìn)行判定:
$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'],
]
*/
values()
values
方法返回一個(gè)鍵經(jīng)過重置成連續(xù)整型索引的新集合:
$collection = collect([
10 => ['product' => 'Desk', 'price' => 200],
11 => ['product' => 'Desl', 'price' => 200],
]);
$values = $collection->values();
$values->all();
/*
[
0 => ['product' => 'Desk', 'price' => 200],
1 => ['product' => 'Desk', 'price' => 200],
]
*/
where()
where
方法根據(jù)指定的鍵值對(duì)來進(jìn)行集合的過濾:
$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
方法會(huì)使用嚴(yán)格的比較模式。你可以使用 whereLoose
方法來使用疏松的比較模式渤涌。
whereLoose()
whereLoose
該方法與 where
方法的運(yùn)作相同佩谣,只是其比較值的方式是疏松模式。
whereIn()
whereIn
方法根據(jù)給定的鍵值對(duì)中的值組來對(duì)集合中的項(xiàng)目進(jìn)行過濾:
$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
方法使用的是嚴(yán)格的比較模式实蓬,如果你需要使用疏松的比較模式請(qǐng)使用 whereInLoose
方法茸俭。
whereInLoose()
該方法與 whereIn
方法的運(yùn)作相同吊履,只是其使用的是疏松的比較模式。
zip()
zip
方法會(huì)根據(jù)相應(yīng)的索引將給定的數(shù)組中的值與集合中項(xiàng)目的值進(jìn)行合并:
$collection = collect(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]