跳到內容

集合

簡介

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]);

Eloquent 查詢的結果始終以 Collection 實例傳回。

擴展集合

集合是「可巨集化的」,這允許您在執行時將其他方法新增至 Collection 類別。Illuminate\Support\Collection 類別的 macro 方法接受一個 Closure,當呼叫您的巨集時,將會執行該 Closure。巨集 Closure 可以透過 $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()

after() 方法會傳回指定項目之後的項目。如果找不到指定項目或該項目為最後一個項目,則會傳回 null

1$collection = collect([1, 2, 3, 4, 5]);
2 
3$collection->after(3);
4 
5// 4
6 
7$collection->after(5);
8 
9// null

此方法使用「寬鬆」比較搜尋指定項目,這表示包含整數值的字串會被視為等於相同值的整數。若要使用「嚴格」比較,您可以將 strict 引數提供給方法

1collect([2, 4, 6, 8])->after('4', strict: true);
2 
3// null

或者,您可以提供自己的 Closure 以搜尋通過給定真值測試的第一個項目

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()

before() 方法與 after 方法相反。它會傳回指定項目之前的項目。如果找不到指定項目或該項目為第一個項目,則會傳回 null

1$collection = collect([1, 2, 3, 4, 5]);
2 
3$collection->before(3);
4 
5// 2
6 
7$collection->before(1);
8 
9// null
10 
11collect([2, 4, 6, 8])->before('4', strict: true);
12 
13// null
14 
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 @endforeach
6 </div>
7@endforeach

chunkWhile()

chunkWhile() 方法會根據給定回呼的評估,將集合分割成多個較小的集合。傳遞給 Closure 的 $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]

當您有一個 Enumerable 實例並且需要非惰性集合實例時,collect() 方法特別有用。由於 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() 方法會將給定的 array 或集合的值附加到另一個集合的末尾

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() 方法會判斷集合是否包含給定項目。您可以將 Closure 傳遞給 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// true
6 
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// false

containsStrict()

此方法具有與 contains 方法相同的簽名;但是,所有值都使用「嚴格」比較進行比較。

當使用 Eloquent 集合 時,此方法的行為會被修改。

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]

您可以將 Closure 傳遞給 countBy() 方法,以依自訂值計算所有項目

1$collection = collect(['[email protected]', '[email protected]', '[email protected]']);
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 Collection {
7 #items: array:2 [
8 0 => "John Doe"
9 1 => "Jane Doe"
10 ]
11 }
12*/

如果您不想停止執行腳本,請改用 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 集合 時,此方法的行為會被修改。

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 的說明,這是 diffAssocUsing 方法在內部使用的 PHP 函式。

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() 方法會判斷集合是否不包含給定項目。您可以將 Closure 傳遞給 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// true
6 
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 
2``````php
3$collection = collect(['John Doe', 'Jane Doe']);
4 
5$collection->dump();
6 
7/*
8 Collection {
9 #items: array:2 [
10 0 => "John Doe"
11 1 => "Jane Doe"
12 ]
13 }
14*/

如果您想在傾印集合後停止執行腳本,請改用 dd 方法。

duplicates()

duplicates() 方法會從集合中檢索並傳回重複的值

1 
2``````php
3$collection = collect(['a', 'b', 'a', 'c', 'b']);
4 
5$collection->duplicates();
6 
7// [2 => 'a', 4 => 'b']

如果集合包含陣列或物件,您可以傳遞您想要檢查重複值的屬性的鍵

1 
2``````php
3$employees = collect([
4 ['email' => '[email protected]', 'position' => 'Developer'],
5 ['email' => '[email protected]', 'position' => 'Designer'],
6 ['email' => '[email protected]', 'position' => 'Developer'],
7]);
8 
9$employees->duplicates('position');
10 
11// [2 => 'Developer']

duplicatesStrict()

此方法具有與 duplicates 方法相同的簽名;但是,所有值都使用「嚴格」比較進行比較。

each()

each() 方法會迭代集合中的項目,並將每個項目傳遞給 Closure

1$collection = collect([1, 2, 3, 4]);
2 
3$collection->each(function (int $item, int $key) {
4 // ...
5});

如果您想停止迭代項目,您可以從您的 Closure 傳回 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]);

也可以指定原始類型,例如 stringintfloatboolarray

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 集合 時,此方法的行為會被修改。

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 的反向操作,請參閱 reject 方法。

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() 方法將傳回給定項目鍵的值為「truthy」的第一個項目

1$collection->firstWhere('age');
2 
3// ['name' => 'Linda', 'age' => 14]

flatMap()

flatMap() 方法會迭代集合並將每個值傳遞給給定的 Closure。Closure 可以自由修改項目並傳回它,從而形成一個新的修改項目集合。然後,陣列會被扁平化一層

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]

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 '[email protected]';
3});
4 

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// true
10 
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// true
6 
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

如果集合包含簡單的字串或數值,您應該將「膠水」作為方法的唯一引數傳遞

1collect([1, 2, 3, 4, 5])->implode('-');
2 
3// '1-2-3-4-5'

如果您想格式化要聯結的值,您可以將 Closure 傳遞給 implode() 方法

1$collection->implode(function (array $item, int $key) {
2 return strtoupper($item['product']);
3}, ', ');
4 
5// DESK, CHAIR

intersect()

intersect() 方法會從原始集合中移除任何不存在於給定 array 或集合中的值。結果集合將保留原始集合的鍵

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 集合 時,此方法的行為會被修改。

intersectUsing()

intersectUsing() 方法會從原始集合中移除任何不存在於給定 array 或集合中的值,並使用自訂回呼來比較值。結果集合將保留原始集合的鍵

1$collection = collect(['Desk', 'Sofa', 'Chair']);
2 
3$intersect = $collection->intersectUsing(['desk', 'chair', 'bookcase'], function ($a, $b) {
4 return strcasecmp($a, $b);
5});
6 
7$intersect->all();
8 
9// [0 => 'Desk', 2 => 'Chair']

intersectAssoc()

intersectAssoc() 方法會將原始集合與另一個集合或 array 進行比較,傳回存在於所有給定集合中的鍵/值對

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() 方法會將原始集合與另一個集合或 array 進行比較,傳回同時存在於兩者中的鍵/值對,並使用自訂比較回呼來判斷鍵和值的相等性

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 ($a, $b) {
12 return strcasecmp($a, $b);
13});
14 
15$intersect->all();
16 
17// ['Size' => 'M']

intersectByKeys()

intersectByKeys() 方法會從原始集合中移除任何不存在於給定 array 或集合中的鍵及其對應的值

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\LazyCollection
6 
7$lazyCollection->all();
8 
9// [1, 2, 3, 4]

當您需要對包含大量項目的龐大 Collection 執行轉換時,這特別有用。

1$count = $hugeCollection
2 ->lazy()
3 ->where('country', 'FR')
4 ->where('balance', '>', '100')
5 ->count();

透過將集合轉換為 LazyCollection,我們可以避免分配大量的額外記憶體。雖然原始集合仍然將值保留在記憶體中,但後續的篩選則不會。因此,在篩選集合結果時,實際上不會分配額外的記憶體。

macro()

靜態 macro 方法允許您在執行時期將方法新增至 Collection 類別。請參閱 擴充集合 的文件以取得更多資訊。

make()

靜態 make 方法會建立一個新的集合實例。請參閱 建立集合 章節。

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' => '[email protected]',
6 ],
7 [
8 'name' => 'Jane',
9 'department' => 'Marketing',
10 'email' => '[email protected]',
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 '[email protected]' => 'John',
23 '[email protected]' => '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// 10
4 
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' => '[email protected]'],
3 ['name' => 'User #2', 'email' => '[email protected]'],
4])->multiply(3);
5 
6/*
7 [
8 ['name' => 'User #1', 'email' => '[email protected]'],
9 ['name' => 'User #2', 'email' => '[email protected]'],
10 ['name' => 'User #1', 'email' => '[email protected]'],
11 ['name' => 'User #2', 'email' => '[email protected]'],
12 ['name' => 'User #1', 'email' => '[email protected]'],
13 ['name' => 'User #2', 'email' => '[email protected]'],
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 方法會使用給定的值填滿陣列,直到陣列達到指定的尺寸。此方法的行為類似於 array_pad PHP 函式。

若要向左邊填補,您應該指定負數尺寸。如果給定尺寸的絕對值小於或等於陣列的長度,則不會進行填補。

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]

percentage()

percentage 方法可用於快速判斷集合中通過給定真值測試的項目百分比。

1$collection = collect([1, 1, 2, 2, 2, 3]);
2 
3$percentage = $collection->percentage(fn ($value) => $value === 1);
4 
5// 33.33

預設情況下,百分比將四捨五入到小數點後兩位。但是,您可以透過為此方法提供第二個參數來自訂此行為。

1$percentage = $collection->percentage(fn ($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']]

如果存在重複的鍵值,則最後一個相符的元素將插入到 plucked 集合中。

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 方法會移除並傳回集合中的最後一個項目。

1$collection = collect([1, 2, 3, 4, 5]);
2 
3$collection->pop();
4 
5// 5
6 
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, int $key) use ($ratio) {
14 return $carry + ($value * $ratio[$key]);
15});
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 方法的反向操作,請參閱 filter 方法。

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()

此方法的作用與 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 方法會在集合中搜尋給定的值,如果找到則傳回其鍵值。如果找不到該項目,則傳回 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

或者,您可以提供自己的 Closure 以搜尋通過給定真值測試的第一個項目

1collect([2, 4, 6, 8])->search(function (int $item, int $key) {
2 return $item > 5;
3});
4 
5// 2

select()

select 方法會從集合中選取給定的鍵值,類似於 SQL SELECT 陳述式。

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// 1
6 
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()

當給定的回呼函式傳回 false 時,skipUntil 方法會略過集合中的項目。一旦回呼函式傳回 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()

當給定的回呼函式傳回 true 時,skipWhile 方法會略過集合中的項目。一旦回呼函式傳回 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 方法在內部使用的函式。

如果您需要排序巢狀陣列或物件的集合,請參閱 sortBysortByDesc 方法。

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*/

回呼函式必須是一個比較函式,它傳回一個小於、等於或大於零的整數。如需更多資訊,請參閱 PHP 文件中關於 uksort 的說明,這是 sortKeysUsing 方法在內部使用的 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]

與大多數其他集合方法不同,transform 會修改集合本身。如果您想要建立新的集合,請改用 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()

此方法具有與 unique 方法相同的簽章;但是,所有值都使用「嚴格」比較進行比較。

unless()

除非給定給此方法的第一個參數評估為 true,否則 unless 方法將執行給定的回呼函式。

1$collection = collect([1, 2, 3]);
2 
3$collection->unless(true, function (Collection $collection) {
4 return $collection->push(4);
5});
6 
7$collection->unless(false, function (Collection $collection) {
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) {
4 return $collection->push(4);
5}, function (Collection $collection) {
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()

當給定給此方法的第一個參數評估為 true 時,when 方法將執行給定的回呼函式。集合實例和給定給 when 方法的第一個參數將提供給閉包。

1$collection = collect([1, 2, 3]);
2 
3$collection->when(true, function (Collection $collection, int $value) {
4 return $collection->push(4);
5});
6 
7$collection->when(false, function (Collection $collection, int $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, int $value) {
4 return $collection->push(4);
5}, function (Collection $collection) {
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]]

高階訊息

集合也提供對「高階訊息」的支援,這些是針對集合執行常見動作的快捷方式。提供高階訊息的集合方法包括:averageavgcontainseacheveryfilterfirstflatMapgroupBykeyBymapmaxminpartitionrejectskipUntilskipWhilesomesortBysortByDescsumtakeUntiltakeWhileunique

每個高階訊息都可以作為集合實例上的動態屬性存取。例如,讓我們使用 each 高階訊息來呼叫集合中每個物件上的方法。

1use App\Models\User;
2 
3$users = User::where('votes', '>', 500)->get();
4 
5$users->each->markAsVip();

同樣地,我們可以利用 sum 高階訊息來收集使用者集合的「votes」總數。

1$users = User::where('group', 'Development')->get();
2 
3return $users->sum->votes;

惰性集合

簡介

在深入了解 Laravel 的惰性集合之前,請花一些時間熟悉 PHP generators

為了補充已經功能強大的 Collection 類別,LazyCollection 類別利用 PHP 的 generators,讓您能夠處理非常龐大的資料集,同時保持低記憶體使用量。

例如,假設您的應用程式需要處理數 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})->chunk(4)->map(function (array $lines) {
11 return LogEntry::fromLines($lines);
12})->each(function (LogEntry $logEntry) {
13 // Process the log entry...
14});

或者,假設您需要迭代 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 generator 函式傳遞給集合的 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});

Enumerable 合約

Collection 類別上幾乎所有可用的方法也都可在 LazyCollection 類別上使用。這兩個類別都實作了 Illuminate\Support\Enumerable contract,它定義了以下方法:

會變更集合的方法(例如 shiftpopprepend 等)在 LazyCollection 類別上是無法使用的。

惰性集合方法

除了 Enumerable contract 中定義的方法之外,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// 1
11// 2
12// ...
13// 58
14// 59

為了說明此方法的使用方式,假設一個應用程式使用 cursor 從資料庫提交發票。您可以定義一個每 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// 1
10// 2
11// 3

throttle()

throttle 方法將節流惰性集合,以便在指定的秒數之後傳回每個值。此方法對於您可能與外部 API 互動且這些 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();