跳轉至內容

集合 (Collections)

簡介

Illuminate\Support\Collection 類為處理資料陣列提供了流暢、便捷的包裝器。例如,請看以下程式碼。我們將使用 collect 輔助函式從陣列建立一個新的集合例項,對每個元素執行 strtoupper 函式,然後刪除所有空元素:

1$collection = collect(['Taylor', 'Abigail', null])->map(function (?string $name) {
2 return strtoupper($name);
3})->reject(function (string $name) {
4 return empty($name);
5});

如你所見,Collection 類允許你鏈式呼叫其方法,從而對底層陣列執行流暢的對映和歸約操作。通常情況下,集合是不可變的,這意味著每個 Collection 方法都會返回一個全新的 Collection 例項。

建立集合

如上所述,collect 輔助函式會針對給定陣列返回一個新的 Illuminate\Support\Collection 例項。因此,建立集合非常簡單:

1$collection = collect([1, 2, 3]);

你也可以使用 makefromJson 方法來建立集合。

Eloquent 查詢的結果始終以 Collection 例項形式返回。

擴充套件集合

集合支援“宏”(macroable),這允許你在執行時向 Collection 類新增額外的方法。Illuminate\Support\Collection 類的 macro 方法接受一個閉包,當你的宏被呼叫時,該閉包就會執行。宏閉包可以透過 $this 訪問集合的其他方法,就像它是集合類的真實方法一樣。例如,以下程式碼為 Collection 類添加了一個 toUpper 方法:

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');
13 
14// ['primero', 'segundo'];

可用方法

在本章後續的集合文件中,我們將討論 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

或者,你可以提供自己的閉包來搜尋透過給定真值測試的第一個專案。

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 方法根據給定回撥的評估結果將集合拆分為多個較小的集合。傳遞給閉包的 $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 方法將給定陣列或集合的值追加到另一個集合的末尾。

1$collection = collect(['John Doe']);
2 
3$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
4 
5$concatenated->all();
6 
7// ['John Doe', 'Jane Doe', 'Johnny Doe']

concat 方法會為連線到原始集合的專案重新索引數字鍵。若要在關聯集合中維護鍵,請參閱 merge 方法。

contains()

contains 方法確定集合是否包含給定專案。你可以向 contains 方法傳遞一個閉包,以確定集合中是否存在匹配給定真值測試的元素。

1$collection = collect([1, 2, 3, 4, 5]);
2 
3$collection->contains(function (int $value, int $key) {
4 return $value > 5;
5});
6 
7// false

或者,你可以向 contains 方法傳遞一個字串,以確定集合是否包含給定的專案值。

1$collection = collect(['name' => 'Desk', 'price' => 100]);
2 
3$collection->contains('Desk');
4 
5// 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 方法。

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]

你可以向 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 array:2 [
7 0 => "John Doe"
8 1 => "Jane Doe"
9 ]
10*/

如果你不想停止執行指令碼,請改用 dump 方法。

diff()

diff 方法根據值將集合與另一個集合或普通 PHP array 進行比較。此方法將返回存在於原始集合中但不存在於給定集合中的值。

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

使用 Eloquent 集合 時,此方法的行為會發生改變。

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 方法確定集合是否不包含給定專案。你可以向 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 方法在檢查專案值時使用“鬆散”比較,這意味著具有整數值的字串將被視為等於相同值的整數。

doesntContainStrict()

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

dot()

dot 方法將多維集合展平為單層集合,並使用“點”符號來表示深度。

1$collection = collect(['products' => ['desk' => ['price' => 100]]]);
2 
3$flattened = $collection->dot();
4 
5$flattened->all();
6 
7// ['products.desk.price' => 100]

dump()

dump 方法列印集合的專案。

1$collection = collect(['John Doe', 'Jane Doe']);
2 
3$collection->dump();
4 
5/*
6 array:2 [
7 0 => "John Doe"
8 1 => "Jane Doe"
9 ]
10*/

如果你想在列印集合後停止執行指令碼,請改用 dd 方法。

duplicates()

duplicates 方法檢索並返回集合中的重複值。

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

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

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

duplicatesStrict()

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

each()

each 方法迭代集合中的專案,並將每個專案傳遞給閉包。

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

如果你想停止迭代專案,可以從閉包中返回 false

1$collection->each(function (int $item, int $key) {
2 if (/* condition */) {
3 return false;
4 }
5});

eachSpread()

eachSpread 方法迭代集合中的專案,並將每個巢狀專案的值傳遞給給定的回撥。

1$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);
2 
3$collection->eachSpread(function (string $name, int $age) {
4 // ...
5});

你可以透過從回撥中返回 false 來停止迭代專案。

1$collection->eachSpread(function (string $name, int $age) {
2 return false;
3});

ensure()

ensure 方法可用於驗證集合的所有元素是否屬於給定型別或型別列表。否則,將丟擲 UnexpectedValueException

1return $collection->ensure(User::class);
2 
3return $collection->ensure([User::class, Customer::class]);

也可以指定諸如 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 方法將返回給定專案鍵的值為“真”的第一個專案。

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

flatMap()

flatMap 方法遍歷集合並將每個值傳遞給給定的閉包。閉包可以自由修改專案並返回它,從而形成一個新的修改後專案的集合。然後,陣列將被展平一級。

1$collection = collect([
2 ['name' => 'Sally'],
3 ['school' => 'Arkansas'],
4 ['age' => 28]
5]);
6 
7$flattened = $collection->flatMap(function (array $values) {
8 return array_map('strtoupper', $values);
9});
10 
11$flattened->all();
12 
13// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];

flatten()

flatten 方法將多維集合展平為一維。

1$collection = collect([
2 'name' => 'Taylor',
3 'languages' => [
4 'PHP', 'JavaScript'
5 ]
6]);
7 
8$flattened = $collection->flatten();
9 
10$flattened->all();
11 
12// ['Taylor', 'PHP', 'JavaScript'];

如有必要,你可以向 flatten 方法傳遞一個“深度”引數。

1$collection = collect([
2 'Apple' => [
3 [
4 'name' => 'iPhone 6S',
5 'brand' => 'Apple'
6 ],
7 ],
8 'Samsung' => [
9 [
10 'name' => 'Galaxy S7',
11 'brand' => 'Samsung'
12 ],
13 ],
14]);
15 
16$products = $collection->flatten(1);
17 
18$products->values()->all();
19 
20/*
21 [
22 ['name' => 'iPhone 6S', 'brand' => 'Apple'],
23 ['name' => 'Galaxy S7', 'brand' => 'Samsung'],
24 ]
25*/

在此示例中,如果不提供深度而呼叫 flatten,也會展平巢狀陣列,結果為 ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']。提供深度允許你指定展平巢狀陣列的層數。

flip()

flip 方法交換集合的鍵及其對應的值。

1$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
2 
3$flipped = $collection->flip();
4 
5$flipped->all();
6 
7// ['Taylor' => 'name', 'Laravel' => 'framework']

forget()

forget 方法透過鍵從集合中刪除一個專案。

1$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
2 
3// Forget a single key...
4$collection->forget('name');
5 
6// ['framework' => 'Laravel']
7 
8// Forget multiple keys...
9$collection->forget(['name', 'framework']);
10 
11// []

與大多數其他集合方法不同,forget 不會返回新的修改後的集合;它會直接修改並返回呼叫它的集合。

forPage()

forPage 方法返回一個包含給定頁碼上可能存在的專案的新集合。該方法接受頁碼作為第一個引數,每頁顯示的項數作為第二個引數。

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

fromJson()

靜態 fromJson 方法透過使用 PHP 的 json_decode 函式解碼給定 JSON 字串來建立新的集合例項。

1use Illuminate\Support\Collection;
2 
3$json = json_encode([
4 'name' => 'Taylor Otwell',
5 'role' => 'Developer',
6 'status' => 'Active',
7]);
8 
9$collection = Collection::fromJson($json);

get()

get 方法返回給定鍵處的專案。如果鍵不存在,則返回 null

1$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
2 
3$value = $collection->get('name');
4 
5// Taylor

你可以選擇傳遞預設值作為第二個引數。

1$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
2 
3$value = $collection->get('age', 34);
4 
5// 34

你甚至可以將回調作為方法的預設值傳遞。如果指定的鍵不存在,將返回回撥的結果。

1$collection->get('email', function () {
2 return '[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

hasMany()

hasMany 方法確定集合是否包含多個專案。

1collect([])->hasMany();
2 
3// false
4 
5collect(['1'])->hasMany();
6 
7// false
8 
9collect([1, 2, 3])->hasMany();
10 
11// true
12 
13collect([
14 ['age' => 2],
15 ['age' => 3],
16])->hasMany(fn ($item) => $item['age'] === 2)
17 
18// false

hasSole()

hasSole 方法確定集合是否包含單個專案(可選擇匹配給定的條件)。

1collect([])->hasSole();
2 
3// false
4 
5collect(['1'])->hasSole();
6 
7// true
8 
9collect([1, 2, 3])->hasSole(fn (int $item) => $item === 2);
10 
11// true

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'

如果你想格式化正在連線的值,可以向 implode 方法傳遞閉包。

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

intersect()

intersect 方法從原始集合中刪除任何不存在於給定陣列或集合中的值。結果集合將保留原始集合的鍵。

1$collection = collect(['Desk', 'Sofa', 'Chair']);
2 
3$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
4 
5$intersect->all();
6 
7// [0 => 'Desk', 2 => 'Chair']

使用 Eloquent 集合 時,此方法的行為會發生改變。

intersectUsing()

intersectUsing 方法使用自定義回撥來比較值,從原始集合中刪除任何不存在於給定陣列或集合中的值。結果集合將保留原始集合的鍵。

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

intersectAssoc()

intersectAssoc 方法將原始集合與另一個集合或陣列進行比較,返回存在於所有給定集合中的鍵/值對。

1$collection = collect([
2 'color' => 'red',
3 'size' => 'M',
4 'material' => 'cotton'
5]);
6 
7$intersect = $collection->intersectAssoc([
8 'color' => 'blue',
9 'size' => 'M',
10 'material' => 'polyester'
11]);
12 
13$intersect->all();
14 
15// ['size' => 'M']

intersectAssocUsing()

intersectAssocUsing 方法將原始集合與另一個集合或陣列進行比較,使用自定義比較回撥來確定鍵和值是否相等,返回兩者中都存在的鍵/值對。

1$collection = collect([
2 'color' => 'red',
3 'Size' => 'M',
4 'material' => 'cotton',
5]);
6 
7$intersect = $collection->intersectAssocUsing([
8 'color' => 'blue',
9 'size' => 'M',
10 'material' => 'polyester',
11], function (string $a, string $b) {
12 return strcasecmp($a, $b);
13});
14 
15$intersect->all();
16 
17// ['Size' => 'M']

intersectByKeys()

intersectByKeys 方法從原始集合中刪除任何鍵及其對應值,這些鍵不存在於給定陣列或集合中。

1$collection = collect([
2 'serial' => 'UX301', 'type' => 'screen', 'year' => 2009,
3]);
4 
5$intersect = $collection->intersectByKeys([
6 'reference' => 'UX404', 'type' => 'tab', 'year' => 2011,
7]);
8 
9$intersect->all();
10 
11// ['type' => 'screen', 'year' => 2009]

isEmpty()

如果集合為空,isEmpty 方法返回 true;否則返回 false

1collect([])->isEmpty();
2 
3// true

isNotEmpty()

如果集合不為空,isNotEmpty 方法返回 true;否則返回 false

1collect([])->isNotEmpty();
2 
3// false

join()

join 方法使用字串連線集合的值。使用此方法的第二個引數,你還可以指定最後一個元素應該如何追加到字串中。

1collect(['a', 'b', 'c'])->join(', '); // 'a, b, c'
2collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'
3collect(['a', 'b'])->join(', ', ' and '); // 'a and b'
4collect(['a'])->join(', ', ' and '); // 'a'
5collect([])->join(', ', ' and '); // ''

keyBy()

keyBy 方法透過給定鍵對集合進行索引。如果多個專案具有相同的鍵,則只有最後一個會出現在新集合中。

1$collection = collect([
2 ['product_id' => 'prod-100', 'name' => 'Desk'],
3 ['product_id' => 'prod-200', 'name' => 'Chair'],
4]);
5 
6$keyed = $collection->keyBy('product_id');
7 
8$keyed->all();
9 
10/*
11 [
12 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
13 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
14 ]
15*/

你也可以向該方法傳遞迴調。回撥應該返回用於索引集合的值。

1$keyed = $collection->keyBy(function (array $item, int $key) {
2 return strtoupper($item['product_id']);
3});
4 
5$keyed->all();
6 
7/*
8 [
9 'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
10 'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
11 ]
12*/

keys()

keys 方法返回集合的所有鍵。

1$collection = collect([
2 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
3 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
4]);
5 
6$keys = $collection->keys();
7 
8$keys->all();
9 
10// ['prod-100', 'prod-200']

last()

last 方法返回集合中透過給定真值測試的最後一個元素。

1collect([1, 2, 3, 4])->last(function (int $value, int $key) {
2 return $value < 3;
3});
4 
5// 2

你也可以在不帶引數的情況下呼叫 last 方法來獲取集合中的最後一個元素。如果集合為空,則返回 null

1collect([1, 2, 3, 4])->last();
2 
3// 4

lazy()

lazy 方法從底層專案陣列返回一個新的 LazyCollection 例項。

1$lazyCollection = collect([1, 2, 3, 4])->lazy();
2 
3$lazyCollection::class;
4 
5// Illuminate\Support\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 方法建立一個新的集合例項。請參閱 建立集合 一節。

1use Illuminate\Support\Collection;
2 
3$collection = Collection::make([1, 2, 3]);

map()

map 方法遍歷集合並將每個值傳遞給給定的回撥。回撥可以自由修改專案並返回它,從而形成一個新的修改後專案的集合。

1$collection = collect([1, 2, 3, 4, 5]);
2 
3$multiplied = $collection->map(function (int $item, int $key) {
4 return $item * 2;
5});
6 
7$multiplied->all();
8 
9// [2, 4, 6, 8, 10]

與大多數其他集合方法一樣,map 返回一個新的集合例項;它不會修改呼叫它的集合。如果你想轉換原始集合,請使用 transform 方法。

mapInto()

mapInto() 方法迭代集合,透過將值傳入建構函式來建立給定類的新例項。

1class Currency
2{
3 /**
4 * Create a new currency instance.
5 */
6 function __construct(
7 public string $code,
8 ) {}
9}
10 
11$collection = collect(['USD', 'EUR', 'GBP']);
12 
13$currencies = $collection->mapInto(Currency::class);
14 
15$currencies->all();
16 
17// [Currency('USD'), Currency('EUR'), Currency('GBP')]

mapSpread()

mapSpread 方法迭代集合中的專案,並將每個巢狀專案的值傳遞給給定的閉包。閉包可以自由修改專案並返回它,從而形成一個新的修改後專案的集合。

1$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2 
3$chunks = $collection->chunk(2);
4 
5$sequence = $chunks->mapSpread(function (int $even, int $odd) {
6 return $even + $odd;
7});
8 
9$sequence->all();
10 
11// [1, 5, 9, 13, 17]

mapToGroups()

mapToGroups 方法根據給定的閉包對集合中的專案進行分組。閉包應該返回一個包含單個鍵/值對的關聯陣列,從而形成一個新的分組值集合。

1$collection = collect([
2 [
3 'name' => 'John Doe',
4 'department' => 'Sales',
5 ],
6 [
7 'name' => 'Jane Doe',
8 'department' => 'Sales',
9 ],
10 [
11 'name' => 'Johnny Doe',
12 'department' => 'Marketing',
13 ]
14]);
15 
16$grouped = $collection->mapToGroups(function (array $item, int $key) {
17 return [$item['department'] => $item['name']];
18});
19 
20$grouped->all();
21 
22/*
23 [
24 'Sales' => ['John Doe', 'Jane Doe'],
25 'Marketing' => ['Johnny Doe'],
26 ]
27*/
28 
29$grouped->get('Sales')->all();
30 
31// ['John Doe', 'Jane Doe']

mapWithKeys()

mapWithKeys 方法遍歷集合並將每個值傳遞給給定的回撥。回撥應該返回一個包含單個鍵/值對的關聯陣列。

1$collection = collect([
2 [
3 'name' => 'John',
4 'department' => 'Sales',
5 'email' => '[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([
2 ['foo' => 10],
3 ['foo' => 20]
4])->min('foo');
5 
6// 10
7 
8$min = collect([1, 2, 3, 4, 5])->min();
9 
10// 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 集合 時,此方法的行為會發生改變。

pad()

pad 方法將陣列填充為給定值,直到達到指定大小。此方法的行為類似於 PHP 的 array_pad 函式。

要向左填充,你應該指定一個負數大小。如果給定大小的絕對值小於或等於陣列長度,則不會進行任何填充。

1$collection = collect(['A', 'B', 'C']);
2 
3$filtered = $collection->pad(5, 0);
4 
5$filtered->all();
6 
7// ['A', 'B', 'C', 0, 0]
8 
9$filtered = $collection->pad(-5, 0);
10 
11$filtered->all();
12 
13// [0, 0, 'A', 'B', 'C']

partition()

partition 方法可以與 PHP 陣列解構相結合,將透過給定真值測試的元素與未透過的元素分開。

1$collection = collect([1, 2, 3, 4, 5, 6]);
2 
3[$underThree, $equalOrAboveThree] = $collection->partition(function (int $i) {
4 return $i < 3;
5});
6 
7$underThree->all();
8 
9// [1, 2]
10 
11$equalOrAboveThree->all();
12 
13// [3, 4, 5, 6]

Eloquent 集合 互動時,此方法的行為會發生改變。

percentage()

percentage 方法可用於快速確定集合中透過給定真值測試的專案的百分比。

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

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

1$percentage = $collection->percentage(fn (int $value) => $value === 1, precision: 3);
2 
3// 33.333

pipe()

pipe 方法將集合傳遞給給定的閉包並返回執行閉包的結果。

1$collection = collect([1, 2, 3]);
2 
3$piped = $collection->pipe(function (Collection $collection) {
4 return $collection->sum();
5});
6 
7// 6

pipeInto()

pipeInto 方法建立給定類的新例項並將集合傳入建構函式。

1class ResourceCollection
2{
3 /**
4 * Create a new ResourceCollection instance.
5 */
6 public function __construct(
7 public Collection $collection,
8 ) {}
9}
10 
11$collection = collect([1, 2, 3]);
12 
13$resource = $collection->pipeInto(ResourceCollection::class);
14 
15$resource->collection->all();
16 
17// [1, 2, 3]

pipeThrough()

pipeThrough 方法將集合傳遞給給定的閉包陣列並返回執行閉包的結果。

1use Illuminate\Support\Collection;
2 
3$collection = collect([1, 2, 3]);
4 
5$result = $collection->pipeThrough([
6 function (Collection $collection) {
7 return $collection->merge([4, 5]);
8 },
9 function (Collection $collection) {
10 return $collection->sum();
11 },
12]);
13 
14// 15

pluck()

pluck 方法檢索給定鍵的所有值。

1$collection = collect([
2 ['product_id' => 'prod-100', 'name' => 'Desk'],
3 ['product_id' => 'prod-200', 'name' => 'Chair'],
4]);
5 
6$plucked = $collection->pluck('name');
7 
8$plucked->all();
9 
10// ['Desk', 'Chair']

你還可以指定希望如何對結果集合進行索引。

1$plucked = $collection->pluck('name', 'product_id');
2 
3$plucked->all();
4 
5// ['prod-100' => 'Desk', 'prod-200' => 'Chair']

pluck 方法還支援使用“點”符號檢索巢狀值。

1$collection = collect([
2 [
3 'name' => 'Laracon',
4 'speakers' => [
5 'first_day' => ['Rosa', 'Judith'],
6 ],
7 ],
8 [
9 'name' => 'VueConf',
10 'speakers' => [
11 'first_day' => ['Abigail', 'Joey'],
12 ],
13 ],
14]);
15 
16$plucked = $collection->pluck('speakers.first_day');
17 
18$plucked->all();
19 
20// [['Rosa', 'Judith'], ['Abigail', 'Joey']]

如果存在重複鍵,最後一個匹配的元素將被插入到被抽取的集合中。

1$collection = collect([
2 ['brand' => 'Tesla', 'color' => 'red'],
3 ['brand' => 'Pagani', 'color' => 'white'],
4 ['brand' => 'Tesla', 'color' => 'black'],
5 ['brand' => 'Pagani', 'color' => 'orange'],
6]);
7 
8$plucked = $collection->pluck('color', 'brand');
9 
10$plucked->all();
11 
12// ['Tesla' => 'black', 'Pagani' => 'orange']

pop()

pop 方法刪除並返回集合中的最後一個專案。如果集合為空,則返回 null

1$collection = collect([1, 2, 3, 4, 5]);
2 
3$collection->pop();
4 
5// 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]

你也可以提供多個專案以追加到集合的末尾。

1$collection = collect([1, 2, 3, 4]);
2 
3$collection->push(5, 6, 7);
4 
5$collection->all();
6 
7// [1, 2, 3, 4, 5, 6, 7]

put()

put 方法在集合中設定給定的鍵和值。

1$collection = collect(['product_id' => 1, 'name' => 'Desk']);
2 
3$collection->put('price', 100);
4 
5$collection->all();
6 
7// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

random()

random 方法從集合中返回一個隨機專案。

1$collection = collect([1, 2, 3, 4, 5]);
2 
3$collection->random();
4 
5// 4 - (retrieved randomly)

你可以向 random 傳遞一個整數來指定要隨機檢索多少個專案。顯式傳遞要接收的專案數時,總是會返回一個專案集合。

1$random = $collection->random(3);
2 
3$random->all();
4 
5// [2, 4, 5] - (retrieved randomly)

如果集合例項中的專案數少於請求數,random 方法將丟擲 InvalidArgumentException

random 方法還接受一個閉包,該閉包將接收當前的集合例項。

1use Illuminate\Support\Collection;
2 
3$random = $collection->random(fn (Collection $items) => min(10, count($items)));
4 
5$random->all();
6 
7// [1, 2, 3, 4, 5] - (retrieved randomly)

range()

range 方法返回一個包含指定範圍內整數的集合。

1$collection = collect()->range(3, 6);
2 
3$collection->all();
4 
5// [3, 4, 5, 6]

reduce()

reduce 方法將集合歸約為單個值,將每次迭代的結果傳入下一次迭代。

1$collection = collect([1, 2, 3]);
2 
3$total = $collection->reduce(function (?int $carry, int $item) {
4 return $carry + $item;
5});
6 
7// 6

第一次迭代時 $carry 的值為 null;但是,你可以透過向 reduce 傳遞第二個引數來指定其初始值。

1$collection->reduce(function (int $carry, int $item) {
2 return $carry + $item;
3}, 4);
4 
5// 10

reduce 方法還會將陣列鍵傳遞給給定的回撥。

1$collection = collect([
2 'usd' => 1400,
3 'gbp' => 1200,
4 'eur' => 1000,
5]);
6 
7$ratio = [
8 'usd' => 1,
9 'gbp' => 1.37,
10 'eur' => 1.22,
11];
12 
13$collection->reduce(function (int $carry, int $value, string $key) use ($ratio) {
14 return $carry + ($value * $ratio[$key]);
15}, 0);
16 
17// 4264

reduceSpread()

reduceSpread 方法將集合歸約為一個值陣列,並將每次迭代的結果傳入下一次迭代。此方法類似於 reduce 方法;但是,它可以接受多個初始值。

1[$creditsRemaining, $batch] = Image::where('status', 'unprocessed')
2 ->get()
3 ->reduceSpread(function (int $creditsRemaining, Collection $batch, Image $image) {
4 if ($creditsRemaining >= $image->creditsRequired()) {
5 $batch->push($image);
6 
7 $creditsRemaining -= $image->creditsRequired();
8 }
9 
10 return [$creditsRemaining, $batch];
11 }, $creditsAvailable, collect());

reject()

reject 方法使用給定的閉包過濾集合。如果專案應該從結果集合中刪除,閉包應該返回 true

1$collection = collect([1, 2, 3, 4]);
2 
3$filtered = $collection->reject(function (int $value, int $key) {
4 return $value > 2;
5});
6 
7$filtered->all();
8 
9// [1, 2]

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

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

或者,你可以提供自己的閉包來搜尋透過給定真值測試的第一個專案。

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

skipUntil 方法在給定回撥返回 false 時跳過集合中的專案。一旦回撥返回 true,所有剩餘的專案將作為新集合返回。

1$collection = collect([1, 2, 3, 4]);
2 
3$subset = $collection->skipUntil(function (int $item) {
4 return $item >= 3;
5});
6 
7$subset->all();
8 
9// [3, 4]

你也可以向 skipUntil 方法傳遞一個簡單值,以跳過所有專案直到找到給定值。

1$collection = collect([1, 2, 3, 4]);
2 
3$subset = $collection->skipUntil(3);
4 
5$subset->all();
6 
7// [3, 4]

如果未找到給定值,或者回調從未返回 true,則 skipUntil 方法將返回一個空集合。

skipWhile()

skipWhile 方法在給定回撥返回 true 時跳過集合中的專案。一旦回撥返回 false,所有剩餘的專案將作為新集合返回。

1$collection = collect([1, 2, 3, 4]);
2 
3$subset = $collection->skipWhile(function (int $item) {
4 return $item <= 3;
5});
6 
7$subset->all();
8 
9// [4]

如果回撥從未返回 false,則 skipWhile 方法將返回一個空集合。

slice()

slice 方法返回從給定索引開始的集合切片。

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

如果你想限制返回切片的大小,將所需大小作為第二個引數傳遞給該方法。

1$slice = $collection->slice(4, 2);
2 
3$slice->all();
4 
5// [5, 6]

返回的切片預設保留鍵。如果你不想保留原始鍵,可以使用 values 方法重新索引它們。

sliding()

sliding 方法返回一個新的塊集合,代表集合中專案的“滑動視窗”檢視。

1$collection = collect([1, 2, 3, 4, 5]);
2 
3$chunks = $collection->sliding(2);
4 
5$chunks->toArray();
6 
7// [[1, 2], [2, 3], [3, 4], [4, 5]]

這與 eachSpread 方法結合使用特別有用。

1$transactions->sliding(2)->eachSpread(function (Collection $previous, Collection $current) {
2 $current->total = $previous->total + $current->amount;
3});

你可以選擇傳遞第二個“步長”值,它決定了每個塊的第一個專案之間的距離。

1$collection = collect([1, 2, 3, 4, 5]);
2 
3$chunks = $collection->sliding(3, step: 2);
4 
5$chunks->toArray();
6 
7// [[1, 2, 3], [3, 4, 5]]

sole()

sole 方法返回集合中透過給定真值測試的第一個元素,但前提是真值測試僅匹配一個元素。

1collect([1, 2, 3, 4])->sole(function (int $value, int $key) {
2 return $value === 2;
3});
4 
5// 2

你也可以向 sole 方法傳遞鍵/值對,它將返回集合中匹配給定對的第一個元素,但前提是完全匹配一個元素。

1$collection = collect([
2 ['product' => 'Desk', 'price' => 200],
3 ['product' => 'Chair', 'price' => 100],
4]);
5 
6$collection->sole('product', 'Chair');
7 
8// ['product' => 'Chair', 'price' => 100]

或者,如果沒有元素,你也可以在不帶引數的情況下呼叫 sole 方法,以獲取集合中僅有的一個元素。

1$collection = collect([
2 ['product' => 'Desk', 'price' => 200],
3]);
4 
5$collection->sole();
6 
7// ['product' => 'Desk', 'price' => 200]

如果集合中沒有應由 sole 方法返回的元素,將丟擲 \Illuminate\Collections\ItemNotFoundException 異常。如果有多個元素應被返回,將丟擲 \Illuminate\Collections\MultipleItemsFoundException

some()

contains 方法的別名。

sort()

sort 方法對集合進行排序。排序後的集合保留原始陣列鍵,因此在以下示例中,我們將使用 values 方法將鍵重置為連續編號的索引。

1$collection = collect([5, 3, 1, 2, 4]);
2 
3$sorted = $collection->sort();
4 
5$sorted->values()->all();
6 
7// [1, 2, 3, 4, 5]

如果你的排序需求更高階,你可以將帶有你自己的演算法的閉包傳遞給 sort。請參閱 PHP 關於 uasort 的文件,這是集合的 sort 方法內部呼叫的函式。

如果你需要對巢狀陣列或物件的集合進行排序,請參閱 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}'

toPrettyJson()

toPrettyJson 方法使用 JSON_PRETTY_PRINT 選項將集合轉換為格式化的 JSON 字串。

1$collection = collect(['name' => 'Desk', 'price' => 200]);
2 
3$collection->toPrettyJson();

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

uniqueStrict()

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

unless()

unless 方法將在傳給該方法的第一個引數的計算結果不為 true 時執行給定的回撥。集合例項和傳給 unless 方法的第一個引數將提供給閉包。

1$collection = collect([1, 2, 3]);
2 
3$collection->unless(true, function (Collection $collection, bool $value) {
4 return $collection->push(4);
5});
6 
7$collection->unless(false, function (Collection $collection, bool $value) {
8 return $collection->push(5);
9});
10 
11$collection->all();
12 
13// [1, 2, 3, 5]

可以向 unless 方法傳遞第二個回撥。當傳給 unless 方法的第一個引數的計算結果為 true 時,將執行第二個回撥。

1$collection = collect([1, 2, 3]);
2 
3$collection->unless(true, function (Collection $collection, bool $value) {
4 return $collection->push(4);
5}, function (Collection $collection, bool $value) {
6 return $collection->push(5);
7});
8 
9$collection->all();
10 
11// [1, 2, 3, 5]

關於 unless 的反向操作,請參閱 when 方法。

unlessEmpty()

whenNotEmpty 方法的別名。

unlessNotEmpty()

whenEmpty 方法的別名。

unwrap()

靜態 unwrap 方法在適用時從給定值返回集合的底層專案。

1Collection::unwrap(collect('John Doe'));
2 
3// ['John Doe']
4 
5Collection::unwrap(['John Doe']);
6 
7// ['John Doe']
8 
9Collection::unwrap('John Doe');
10 
11// 'John Doe'

value()

value 方法從集合的第一個元素中檢索給定的值。

1$collection = collect([
2 ['product' => 'Desk', 'price' => 200],
3 ['product' => 'Speaker', 'price' => 400],
4]);
5 
6$value = $collection->value('price');
7 
8// 200

values()

values 方法返回一個鍵已重置為連續整數的新集合。

1$collection = collect([
2 10 => ['product' => 'Desk', 'price' => 200],
3 11 => ['product' => 'Speaker', 'price' => 400],
4]);
5 
6$values = $collection->values();
7 
8$values->all();
9 
10/*
11 [
12 0 => ['product' => 'Desk', 'price' => 200],
13 1 => ['product' => 'Speaker', 'price' => 400],
14 ]
15*/

when()

when 方法將在傳給該方法的第一個引數的計算結果為 true 時執行給定的回撥。集合例項和傳給 when 方法的第一個引數將提供給閉包。

1$collection = collect([1, 2, 3]);
2 
3$collection->when(true, function (Collection $collection, bool $value) {
4 return $collection->push(4);
5});
6 
7$collection->when(false, function (Collection $collection, bool $value) {
8 return $collection->push(5);
9});
10 
11$collection->all();
12 
13// [1, 2, 3, 4]

可以向 when 方法傳遞第二個回撥。當傳給 when 方法的第一個引數的計算結果為 false 時,將執行第二個回撥。

1$collection = collect([1, 2, 3]);
2 
3$collection->when(false, function (Collection $collection, bool $value) {
4 return $collection->push(4);
5}, function (Collection $collection, bool $value) {
6 return $collection->push(5);
7});
8 
9$collection->all();
10 
11// [1, 2, 3, 5]

關於 when 的反向操作,請參閱 unless 方法。

whenEmpty()

whenEmpty 方法將在集合為空時執行給定的回撥。

1$collection = collect(['Michael', 'Tom']);
2 
3$collection->whenEmpty(function (Collection $collection) {
4 return $collection->push('Adam');
5});
6 
7$collection->all();
8 
9// ['Michael', 'Tom']
10 
11$collection = collect();
12 
13$collection->whenEmpty(function (Collection $collection) {
14 return $collection->push('Adam');
15});
16 
17$collection->all();
18 
19// ['Adam']

可以向 whenEmpty 方法傳遞第二個閉包,當集合不為空時將執行該閉包。

1$collection = collect(['Michael', 'Tom']);
2 
3$collection->whenEmpty(function (Collection $collection) {
4 return $collection->push('Adam');
5}, function (Collection $collection) {
6 return $collection->push('Taylor');
7});
8 
9$collection->all();
10 
11// ['Michael', 'Tom', 'Taylor']

關於 whenEmpty 的反向操作,請參閱 whenNotEmpty 方法。

whenNotEmpty()

whenNotEmpty 方法將在集合不為空時執行給定的回撥。

1$collection = collect(['Michael', 'Tom']);
2 
3$collection->whenNotEmpty(function (Collection $collection) {
4 return $collection->push('Adam');
5});
6 
7$collection->all();
8 
9// ['Michael', 'Tom', 'Adam']
10 
11$collection = collect();
12 
13$collection->whenNotEmpty(function (Collection $collection) {
14 return $collection->push('Adam');
15});
16 
17$collection->all();
18 
19// []

可以向 whenNotEmpty 方法傳遞第二個閉包,當集合為空時將執行該閉包。

1$collection = collect();
2 
3$collection->whenNotEmpty(function (Collection $collection) {
4 return $collection->push('Adam');
5}, function (Collection $collection) {
6 return $collection->push('Taylor');
7});
8 
9$collection->all();
10 
11// ['Taylor']

關於 whenNotEmpty 的反向操作,請參閱 whenEmpty 方法。

where()

where 方法透過給定的鍵/值對過濾集合。

1$collection = collect([
2 ['product' => 'Desk', 'price' => 200],
3 ['product' => 'Chair', 'price' => 100],
4 ['product' => 'Bookcase', 'price' => 150],
5 ['product' => 'Door', 'price' => 100],
6]);
7 
8$filtered = $collection->where('price', 100);
9 
10$filtered->all();
11 
12/*
13 [
14 ['product' => 'Chair', 'price' => 100],
15 ['product' => 'Door', 'price' => 100],
16 ]
17*/

where 方法在檢查專案值時使用“鬆散”比較,這意味著具有整數值的字串將被視為等於相同值的整數。使用 whereStrict 方法進行“嚴格”比較過濾,或者使用 whereNullwhereNotNull 方法過濾 null 值。

或者,你可以傳遞比較運算子作為第二個引數。支援的運算子有:'===', '!==', '!=', '==', '=', '<>', '>', '<', '>=', 和 '<='。

1$collection = collect([
2 ['name' => 'Jim', 'platform' => 'Mac'],
3 ['name' => 'Sally', 'platform' => 'Mac'],
4 ['name' => 'Sue', 'platform' => 'Linux'],
5]);
6 
7$filtered = $collection->where('platform', '!=', 'Linux');
8 
9$filtered->all();
10 
11/*
12 [
13 ['name' => 'Jim', 'platform' => 'Mac'],
14 ['name' => 'Sally', 'platform' => 'Mac'],
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 ['name' => 0],
6 ['name' => ''],
7]);
8 
9$filtered = $collection->whereNotNull('name');
10 
11$filtered->all();
12 
13/*
14 [
15 ['name' => 'Desk'],
16 ['name' => 'Bookcase'],
17 ['name' => 0],
18 ['name' => ''],
19 ]
20*/

whereNull()

whereNull 方法返回集合中給定鍵為 null 的專案。

1$collection = collect([
2 ['name' => 'Desk'],
3 ['name' => null],
4 ['name' => 'Bookcase'],
5 ['name' => 0],
6 ['name' => ''],
7]);
8 
9$filtered = $collection->whereNull('name');
10 
11$filtered->all();
12 
13/*
14 [
15 ['name' => null],
16 ]
17*/

wrap()

靜態 wrap 方法在適用時將給定值包裝在集合中。

1use Illuminate\Support\Collection;
2 
3$collection = Collection::wrap('John Doe');
4 
5$collection->all();
6 
7// ['John Doe']
8 
9$collection = Collection::wrap(['John Doe']);
10 
11$collection->all();
12 
13// ['John Doe']
14 
15$collection = Collection::wrap(collect('John Doe'));
16 
17$collection->all();
18 
19// ['John Doe']

zip()

zip 方法將給定陣列的值與原始集合對應索引處的值合併在一起。

1$collection = collect(['Chair', 'Desk']);
2 
3$zipped = $collection->zip([100, 200]);
4 
5$zipped->all();
6 
7// [['Chair', 100], ['Desk', 200]]

高階訊息

集合還支援“高階訊息”,這是對集合執行常見操作的快捷方式。提供高階訊息的集合方法有:average, avg, contains, each, every, filter, first, flatMap, groupBy, keyBy, map, max, min, partition, reject, skipUntil, skipWhile, some, sortBy, sortByDesc, sum, takeUntil, takeWhile, 和 unique

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

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

同樣,我們可以使用 sum 高階訊息來獲取使用者集合的總“投票”數:

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

惰性集合

簡介

在深入瞭解 Laravel 的惰性集合之前,花點時間熟悉一下 PHP 生成器

為了補充已經非常強大的 Collection 類,LazyCollection 類利用 PHP 的 生成器,讓你能夠處理非常大的資料集,同時保持較低的記憶體佔用。

例如,假設你的應用程式需要處理一個數千兆位元組的日誌檔案,同時利用 Laravel 的集合方法來解析日誌。與其一次將整個檔案讀取到記憶體中,不如使用惰性集合,在任何給定時間僅在記憶體中保留檔案的一小部分。

1use App\Models\LogEntry;
2use Illuminate\Support\LazyCollection;
3 
4LazyCollection::make(function () {
5 $handle = fopen('log.txt', 'r');
6 
7 while (($line = fgets($handle)) !== false) {
8 yield $line;
9 }
10 
11 fclose($handle);
12})->chunk(4)->map(function (array $lines) {
13 return LogEntry::fromLines($lines);
14})->each(function (LogEntry $logEntry) {
15 // Process the log entry...
16});

或者,假設你需要遍歷 10,000 個 Eloquent 模型。使用傳統的 Laravel 集合時,所有 10,000 個 Eloquent 模型必須同時載入到記憶體中。

1use App\Models\User;
2 
3$users = User::all()->filter(function (User $user) {
4 return $user->id > 500;
5});

然而,查詢構建器的 cursor 方法返回一個 LazyCollection 例項。這允許你仍然只對資料庫執行單個查詢,但一次只在記憶體中保留一個 Eloquent 模型。在此示例中,filter 回撥直到我們實際單獨遍歷每個使用者時才執行,從而大幅減少了記憶體使用。

1use App\Models\User;
2 
3$users = User::cursor()->filter(function (User $user) {
4 return $user->id > 500;
5});
6 
7foreach ($users as $user) {
8 echo $user->id;
9}

建立惰性集合

要建立惰性集合例項,你應該將 PHP 生成器函式傳遞給集合的 make 方法。

1use Illuminate\Support\LazyCollection;
2 
3LazyCollection::make(function () {
4 $handle = fopen('log.txt', 'r');
5 
6 while (($line = fgets($handle)) !== false) {
7 yield $line;
8 }
9 
10 fclose($handle);
11});

Enumerable 契約

Collection 類上幾乎所有可用的方法在 LazyCollection 類上也可用。這兩個類都實現了 Illuminate\Support\Enumerable 契約,該契約定義了以下方法:

改變集合的方法(如 shift, pop, prepend 等)在 LazyCollection 類上不可用

惰性集合方法

除了 Enumerable 契約中定義的方法外,LazyCollection 類還包含以下方法:

takeUntilTimeout()

takeUntilTimeout 方法返回一個新的惰性集合,該集合將列舉值直到指定的時間。在該時間之後,集合將停止列舉。

1$lazyCollection = LazyCollection::times(INF)
2 ->takeUntilTimeout(now()->plus(minutes: 1));
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

為了說明此方法的用法,想象一個應用程式使用遊標從資料庫提交發票。你可以定義一個每 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 互動的情況。

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

withHeartbeat()

withHeartbeat 方法允許你在列舉惰性集合時以固定的時間間隔執行回撥。這對於需要定期維護任務的長耗時操作特別有用,例如延長鎖或傳送進度更新。

1use Carbon\CarbonInterval;
2use Illuminate\Support\Facades\Cache;
3 
4$lock = Cache::lock('generate-reports', seconds: 60 * 5);
5 
6if ($lock->get()) {
7 try {
8 Report::where('status', 'pending')
9 ->lazy()
10 ->withHeartbeat(
11 CarbonInterval::minutes(4),
12 fn () => $lock->extend(CarbonInterval::minutes(5))
13 )
14 ->each(fn ($report) => $report->process());
15 } finally {
16 $lock->release();
17 }
18}