# 集合
- [簡介](#introduction)
- [創建集合](#creating-collections)
- [擴展集合](#extending-collections)
- [可用方法](#available-methods)
- [高階信息](#higher-order-messages)
<a name="introduction"></a>
## 簡介
`Illuminate\Support\Collection` 類提供了一個更具可讀性和更便于處理數組數據的封裝。具體例子請查看下面代碼。我們使用 `collect` 輔助函數從數組中創建一個新的集合實例,對其中每一個元素執行 `strtoupper` 函數之后再刪除所有的空元素:
$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
return strtoupper($name);
})
->reject(function ($name) {
return empty($name);
});
正如你所見, `Collection` 類允許你鏈式調用其它方法,以達到在底層數組上流暢的執行 map 和 reduce 操作,通常,集合是不可變的,這意味著每一個 `Collection` 方法都會返回一個新的 `Collection` 實例。
<a name="creating-collections"></a>
### 創建集合
如上所述, `collect` 輔助函數會為指定的數組返回一個新的 `Illuminate\Support\Collection` 實例。因此,我們可以這樣輕松的創建一個集合:
$collection = collect([1, 2, 3]);
> {tip} 通常,[Eloquent](/docs/{{version}}/eloquent) 查詢的結果返回的內容都是 `Collection` 實例。
<a name="extending-collections"></a>
### 擴展集合
集合都是「可宏擴展」(macroable)的,它允許你在執行時將其它方法添加到 `Collection` 類。例如,通過下面的代碼在 `Collection` 類中添加一個 `toUpper` 方法:
use Illuminate\Support\Str;
Collection::macro('toUpper', function () {
return $this->map(function ($value) {
return Str::upper($value);
});
});
$collection = collect(['first', 'second']);
$upper = $collection->toUpper();
// ['FIRST', 'SECOND']
通常,你應該在 [服務提供者](/docs/{{version}}/providers) 內聲明集合宏。
<a name="available-methods"></a>
## 可用方法
接下來的文檔內容,我們會探討 `Collection` 類的每個方法。請牢記,所有方法都可以通過鏈式訪問的形式優雅的操作數組。而且,幾乎所有的方法都會返回一個新的 `Collection` 實例,允許你在必要時保存集合的原始副本:
<style>
#collection-method-list > p {
column-count: 3; -moz-column-count: 3; -webkit-column-count: 3;
column-gap: 2em; -moz-column-gap: 2em; -webkit-column-gap: 2em;
}
#collection-method-list a {
display: block;
}
</style>
<div id="collection-method-list" markdown="1">
[all](#method-all)
[average](#method-average)
[avg](#method-avg)
[chunk](#method-chunk)
[collapse](#method-collapse)
[combine](#method-combine)
[concat](#method-concat)
[contains](#method-contains)
[containsStrict](#method-containsstrict)
[count](#method-count)
[crossJoin](#method-crossjoin)
[dd](#method-dd)
[diff](#method-diff)
[diffAssoc](#method-diffassoc)
[diffKeys](#method-diffkeys)
[dump](#method-dump)
[each](#method-each)
[eachSpread](#method-eachspread)
[every](#method-every)
[except](#method-except)
[filter](#method-filter)
[first](#method-first)
[firstWhere](#method-first-where)
[flatMap](#method-flatmap)
[flatten](#method-flatten)
[flip](#method-flip)
[forget](#method-forget)
[forPage](#method-forpage)
[get](#method-get)
[groupBy](#method-groupby)
[has](#method-has)
[implode](#method-implode)
[intersect](#method-intersect)
[intersectByKeys](#method-intersectbykeys)
[isEmpty](#method-isempty)
[isNotEmpty](#method-isnotempty)
[keyBy](#method-keyby)
[keys](#method-keys)
[last](#method-last)
[macro](#method-macro)
[make](#method-make)
[map](#method-map)
[mapInto](#method-mapinto)
[mapSpread](#method-mapspread)
[mapToGroups](#method-maptogroups)
[mapWithKeys](#method-mapwithkeys)
[max](#method-max)
[median](#method-median)
[merge](#method-merge)
[min](#method-min)
[mode](#method-mode)
[nth](#method-nth)
[only](#method-only)
[pad](#method-pad)
[partition](#method-partition)
[pipe](#method-pipe)
[pluck](#method-pluck)
[pop](#method-pop)
[prepend](#method-prepend)
[pull](#method-pull)
[push](#method-push)
[put](#method-put)
[random](#method-random)
[reduce](#method-reduce)
[reject](#method-reject)
[reverse](#method-reverse)
[search](#method-search)
[shift](#method-shift)
[shuffle](#method-shuffle)
[slice](#method-slice)
[some](#method-some)
[sort](#method-sort)
[sortBy](#method-sortby)
[sortByDesc](#method-sortbydesc)
[sortKeys](#method-sortkeys)
[sortKeysDesc](#method-sortkeysdesc)
[splice](#method-splice)
[split](#method-split)
[sum](#method-sum)
[take](#method-take)
[tap](#method-tap)
[times](#method-times)
[toArray](#method-toarray)
[toJson](#method-tojson)
[transform](#method-transform)
[union](#method-union)
[unique](#method-unique)
[uniqueStrict](#method-uniquestrict)
[unless](#method-unless)
[unlessEmpty](#method-unlessempty)
[unlessNotEmpty](#method-unlessnotempty)
[unwrap](#method-unwrap)
[values](#method-values)
[when](#method-when)
[whenEmpty](#method-whenempty)
[whenNotEmpty](#method-whennotempty)
[where](#method-where)
[whereStrict](#method-wherestrict)
[whereBetween](#method-wherebetween)
[whereIn](#method-wherein)
[whereInStrict](#method-whereinstrict)
[whereInstanceOf](#method-whereinstanceof)
[whereNotBetween](#method-wherenotbetween)
[whereNotIn](#method-wherenotin)
[whereNotInStrict](#method-wherenotinstrict)
[wrap](#method-wrap)
[zip](#method-zip)
</div>
<a name="method-listing"></a>
## 方法列表
<style>
#collection-method code {
font-size: 14px;
}
#collection-method:not(.first-collection-method) {
margin-top: 50px;
}
</style>
<a name="method-all"></a>
#### `all()` {#collection-method .first-collection-method}
`all` 方法返回該集合表示的底層數組:
collect([1, 2, 3])->all();
// [1, 2, 3]
<a name="method-average"></a>
#### `average()` {#collection-method}
[`avg`](#method-avg) 方法的別名。
<a name="method-avg"></a>
#### `avg()` {#collection-method}
`avg` 方法返回給定鍵的 [平均值](https://en.wikipedia.org/wiki/Average) :
$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
// 20
$average = collect([1, 1, 2, 4])->avg();
// 2
<a name="method-chunk"></a>
#### `chunk()` {#collection-method}
`chunk` 方法將集合拆成多個給定大小的小集合:
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
這個方法在使用網格系統的 [視圖](/docs/{{version}}/views) 中特別適用,例如 [Bootstrap](https://getbootstrap.com/docs/4.1/layout/grid/)。 想象你有一個 [Eloquent](/docs/{{version}}/eloquent) 模型的集合要在網格中顯示:
@foreach ($products->chunk(3) as $chunk)
<div class="row">
@foreach ($chunk as $product)
<div class="col-xs-4">{{ $product->name }}</div>
@endforeach
</div>
@endforeach
<a name="method-collapse"></a>
#### `collapse()` {#collection-method}
`collapse` 方法將多個數組的集合合并成一個數組的集合:
$collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
$collapsed = $collection->collapse();
$collapsed->all();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
<a name="method-combine"></a>
#### `combine()` {#collection-method}
`combine` 方法可以將一個集合的值作為鍵,再將另一個數組或集合的值作為值合并成一個集合:
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]
<a name="method-concat"></a>
#### `concat()` {#collection-method}
`concat` 方法將給定的 `數組` 或集合值追加到集合的末尾:
$collection = collect(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
$concatenated->all();
// ['John Doe', 'Jane Doe', 'Johnny Doe']
<a name="method-contains"></a>
#### `contains()` {#collection-method}
`contains` 方法判斷集合是否包含指定的集合項:
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->contains('Desk');
// true
$collection->contains('New York');
// false
你也可以使用 `contains` 方法傳遞一組鍵 / 值對,可以判斷該鍵 / 值對是否存在于集合中:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->contains('product', 'Bookcase');
// false
最后,你也可以用 `contains` 方法傳遞一個回調函數來執行自己的真實測試:
$collection = collect([1, 2, 3, 4, 5]);
$collection->contains(function ($value, $key) {
return $value > 5;
});
// false
`contains` 方法在檢查集合項的值時使用「寬松」比較,這意味著具有整數值的字符串將被視為等于相同值的整數。相反 [`containsStrict`](#method-containsstrict) 方法則是使用「嚴格」比較進行過濾。
<a name="method-containsstrict"></a>
#### `containsStrict()` {#collection-method}
這個方法和 [`contains`](#method-contains) 方法類似,但是它卻是使用了「嚴格」比較來比較所有的值。
<a name="method-count"></a>
#### `count()` {#collection-method}
`count` 方法返回這個集合內集合項的總數量:
$collection = collect([1, 2, 3, 4]);
$collection->count();
// 4
<a name="method-crossjoin"></a>
#### `crossJoin()` {#collection-method}
`crossJoin` 方法交叉連接指定數組或集合的值,返回所有可能排列的笛卡爾積:
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b']);
$matrix->all();
/*
[
[1, 'a'],
[1, 'b'],
[2, 'a'],
[2, 'b'],
]
*/
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);
$matrix->all();
/*
[
[1, 'a', 'I'],
[1, 'a', 'II'],
[1, 'b', 'I'],
[1, 'b', 'II'],
[2, 'a', 'I'],
[2, 'a', 'II'],
[2, 'b', 'I'],
[2, 'b', 'II'],
]
*/
<a name="method-dd"></a>
#### `dd()` {#collection-method}
`dd` 方法用于打印集合項并中斷腳本執行:
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/
如果你不想中斷執行腳本,請使用 [`dump`](#method-dump) 方法代替。
<a name="method-diff"></a>
#### `diff()` {#collection-method}
`diff` 方法將集合與其它集合或純 PHP `數組` 進行值的比較。然后返回原集合中存在而指定集合中不存在的值:
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]
<a name="method-diffassoc"></a>
#### `diffAssoc()` {#collection-method}
`diffAssoc` 方法與另外一個集合或基于它的鍵和值的 PHP `數組` 進行比較。這個方法將會返回原集合不存在于指定集合的鍵 / 值對:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6
]);
$diff = $collection->diffAssoc([
'color' => 'yellow',
'type' => 'fruit',
'remain' => 3,
'used' => 6
]);
$diff->all();
// ['color' => 'orange', 'remain' => 6]
<a name="method-diffkeys"></a>
#### `diffKeys()` {#collection-method}
`diffKeys` 方法和另外一個集合或 PHP `數組` 的鍵進行比較,然后返回原集合中存在而指定集合中不存在鍵所對應的鍵 / 值對:
$collection = collect([
'one' => 10,
'two' => 20,
'three' => 30,
'four' => 40,
'five' => 50,
]);
$diff = $collection->diffKeys([
'two' => 2,
'four' => 4,
'six' => 6,
'eight' => 8,
]);
$diff->all();
// ['one' => 10, 'three' => 30, 'five' => 50]
<a name="method-dump"></a>
#### `dump()` {#collection-method}
`dump` 方法用于打印集合項:
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dump();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/
如果要在打印集合后終止執行腳本,請使用 [`dd`](#method-dd) 方法代替。
<a name="method-each"></a>
#### `each()` {#collection-method}
`each` 方法用于循環集合項并將其傳遞到回調函數中:
$collection->each(function ($item, $key) {
//
});
如果你想中斷對集合項的循環,那么就在你的回調函數中返回 `false` :
$collection->each(function ($item, $key) {
if (/* 某些條件 */) {
return false;
}
});
<a name="method-eachspread"></a>
#### `eachSpread()` {#collection-method}
`eachSpread` 方法用于循環集合項,將每個嵌套集合項的值傳遞給回調函數:
$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);
$collection->eachSpread(function ($name, $age) {
//
});
你可以通過在回調函數里返回 `false` 來中斷循環:
$collection->eachSpread(function ($name, $age) {
return false;
});
<a name="method-every"></a>
#### `every()` {#collection-method}
`every` 方法可用于驗證集合中的每一個元素是否通過指定的條件測試:
collect([1, 2, 3, 4])->every(function ($value, $key) {
return $value > 2;
});
// false
如果集合為空, `every` 將返回 true:
$collection = collect([]);
$collection->every(function($value, $key) {
return $value > 2;
});
// true
<a name="method-except"></a>
#### `except()` {#collection-method}
`except` 方法返回集合中除了指定鍵之外的所有集合項:
$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);
$filtered = $collection->except(['price', 'discount']);
$filtered->all();
// ['product_id' => 1]
與 `except` 對應的是 [only](#method-only) 方法。
<a name="method-filter"></a>
#### `filter()` {#collection-method}
`filter` 方法使用給定的回調函數過濾集合,只保留那些通過指定條件測試的集合項,方法調用的結果是具有自定義鍵值的數組,鍵值為該元素在原數組中的默認順序索引鍵:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// ['2' => 3 , '3' => 4]
如果沒有提供回調函數,集合中所有返回 `false` 的元素都會被移除:
$collection = collect([1, 2, 3, null, false, '', 0, []]);
$collection->filter()->all();
// ['0' => 1,'1' => 2,'2' => 3]
與 `filter` 對應的是 [reject](#method-reject) 方法。
<a name="method-first"></a>
#### `first()` {#collection-method}
`first` 方法返回集合中通過指定條件測試的第一個元素:
collect([1, 2, 3, 4])->first(function ($value, $key) {
return $value > 2;
});
// 3
你也可以不傳入參數調用 `first` 方法來獲取集合中的第一個元素。如果集合為空,則會返回 `null` :
collect([1, 2, 3, 4])->first();
// 1
<a name="method-first-where"></a>
#### `firstWhere()` {#collection-method}
`firstWhere` 方法返回集合中含有指定鍵 / 值對的第一個元素:
$collection = collect([
['name' => 'Regena', 'age' => null],
['name' => 'Linda', 'age' => 14],
['name' => 'Diego', 'age' => 23],
['name' => 'Linda', 'age' => 84],
]);
$collection->firstWhere('name', 'Linda');
// ['name' => 'Linda', 'age' => 14]
你也可以使用運算符來調用 `firstWhere` 方法:
$collection->firstWhere('age', '>=', 18);
// ['name' => 'Diego', 'age' => 23]
和 [where](#method-where) 方法一樣,你可以將一個參數傳遞給 `firstWhere` 方法。在這種情況下, `firstWhere` 方法將返回指定鍵的值為「真」的第一個集合項:
$collection->firstWhere('age');
// ['name' => 'Linda', 'age' => 14]
<a name="method-flatmap"></a>
#### `flatMap()` {#collection-method}
`flatMap` 方法遍歷集合并將其中的每個值傳遞到給定的回調函數。可以通過回調函數修改集合項并返回它們,從而形成一個被修改過的新集合。然后,集合轉化的數組是同級的:
$collection = collect([
['name' => 'Sally'],
['school' => 'Arkansas'],
['age' => 28]
]);
$flattened = $collection->flatMap(function ($values) {
return array_map('strtoupper', $values);
});
$flattened->all();
// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];
<a name="method-flatten"></a>
#### `flatten()` {#collection-method}
`flatten` 方法將多維集合轉為一維集合:
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['taylor', 'php', 'javascript'];
你可以選擇性地傳入「深度」參數:
$collection = collect([
'Apple' => [
['name' => 'iPhone 6S', 'brand' => 'Apple'],
],
'Samsung' => [
['name' => 'Galaxy S7', 'brand' => 'Samsung']
],
]);
$products = $collection->flatten(1);
$products->values()->all();
/*
[
['name' => 'iPhone 6S', 'brand' => 'Apple'],
['name' => 'Galaxy S7', 'brand' => 'Samsung'],
]
*/
在這個例子里,調用 `flatten` 時不傳入深度參數的話也會將嵌套數組轉成一維的,然后返回 `['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']`。傳入深度參數能讓你限制設置返回數組的層數。
<a name="method-flip"></a>
#### `flip()` {#collection-method}
`flip` 方法將集合的鍵和對應的值進行互換:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$flipped = $collection->flip();
$flipped->all();
// ['taylor' => 'name', 'laravel' => 'framework']
<a name="method-forget"></a>
#### `forget()` {#collection-method}
`forget` 方法將通過指定的鍵來移除集合中對應的內容:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$collection->forget('name');
$collection->all();
// ['framework' => 'laravel']
> {note} 與大多數集合的方法不同的是, `forget` 不會返回修改后的新集合;它會直接修改原集合。
<a name="method-forpage"></a>
#### `forPage()` {#collection-method}
`forPage` 方法返回一個含有指定頁碼數集合項的新集合。這個方法接受頁碼數作為其第一個參數,每頁顯示的項數作為其第二個參數:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);
$chunk->all();
// [4, 5, 6]
<a name="method-get"></a>
#### `get()` {#collection-method}
`get` 方法返回指定鍵的集合項,如果該鍵在集合中不存在,則返回 `null`:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('name');
// taylor
你可以任選一個默認值作為第二個參數傳遞:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('foo', 'default-value');
// default-value
你甚至可以將一個回調函數作為默認值傳遞。如果指定的鍵不存在,就會返回回調函數的結果:
$collection->get('email', function () {
return 'default-value';
});
// default-value
<a name="method-groupby"></a>
#### `groupBy()` {#collection-method}
`groupBy` 方法根據指定鍵對集合項進行分組:
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->toArray();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
你可以傳遞一個回調函數用來代替一個字符串的 `鍵`。這個回調函數應該返回你希望用來分組的鍵的值:
$grouped = $collection->groupBy(function ($item, $key) {
return substr($item['account_id'], -3);
});
$grouped->toArray();
/*
[
'x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
可以傳遞一個數組用于多重分組標準。每一個數組元素將對應多維數組內的相應級別:
$data = new Collection([
10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
]);
$result = $data->groupBy([
'skill',
function ($item) {
return $item['roles'];
},
], $preserveKeys = true);
/*
[
1 => [
'Role_1' => [
10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
],
'Role_2' => [
20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
],
'Role_3' => [
10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
],
],
2 => [
'Role_1' => [
30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
],
'Role_2' => [
40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
],
],
];
*/
<a name="method-has"></a>
#### `has()` {#collection-method}
`has` 方法判斷集合中是否存在指定鍵:
$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
$collection->has('product');
// true
$collection->has(['product', 'amount']);
// true
$collection->has(['amount', 'price']);
// false
<a name="method-implode"></a>
#### `implode()` {#collection-method}
`implode` 方法用于合并集合項。其參數取決于集合項的類型。如果集合包含數組或對象,你應該傳遞你希望合并的屬性的鍵,以及你希望放在值之間用來「拼接」的字符串:
$collection = collect([
['account_id' => 1, 'product' => 'Desk'],
['account_id' => 2, 'product' => 'Chair'],
]);
$collection->implode('product', ', ');
// Desk, Chair
如果集合中包含簡單的字符串或數值,只需要傳入「拼接」用的字符串作為該方法的唯一參數即可:
collect([1, 2, 3, 4, 5])->implode('-');
// '1-2-3-4-5'
<a name="method-intersect"></a>
#### `intersect()` {#collection-method}
`intersect` 方法從原集合中移除在指定 `數組` 或集合中不存在的任何值。生成的集合將會保留原集合的鍵:
$collection = collect(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']
<a name="method-intersectbykeys"></a>
#### `intersectByKeys()` {#collection-method}
`intersectByKeys` 方法從原集合中移除在指定 `數組` 或集合中不存在的任何鍵:
$collection = collect([
'serial' => 'UX301', 'type' => 'screen', 'year' => 2009
]);
$intersect = $collection->intersectByKeys([
'reference' => 'UX404', 'type' => 'tab', 'year' => 2011
]);
$intersect->all();
// ['type' => 'screen', 'year' => 2009]
<a name="method-isempty"></a>
#### `isEmpty()` {#collection-method}
如果集合為空,`isEmpty` 方法返回 `true`,否則,返回 `false`:
collect([])->isEmpty();
// true
<a name="method-isnotempty"></a>
#### `isNotEmpty()` {#collection-method}
如果集合不為空,`isNotEmpty` 方法返回 `true`,否則,返回 `false`:
collect([])->isNotEmpty();
// false
<a name="method-keyby"></a>
#### `keyBy()` {#collection-method}
`keyBy` 方法以指定的鍵作為集合的鍵。如果多個集合項具有相同的鍵,則只有最后一個集合項會顯示在新集合中:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keyed = $collection->keyBy('product_id');
$keyed->all();
/*
[
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
你還可以在這個方法傳遞一個回調函數。該回調函數返回的值會作為該集合的鍵:
$keyed = $collection->keyBy(function ($item) {
return strtoupper($item['product_id']);
});
$keyed->all();
/*
[
'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
<a name="method-keys"></a>
#### `keys()` {#collection-method}
`keys` 方法返回集合中所有的鍵:
$collection = collect([
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keys = $collection->keys();
$keys->all();
// ['prod-100', 'prod-200']
<a name="method-last"></a>
#### `last()` {#collection-method}
`last` 方法返回集合中通過指定條件測試的最后一個元素:
collect([1, 2, 3, 4])->last(function ($value, $key) {
return $value < 3;
});
// 2
你也可以不傳入參數調用 `last` 方法來獲取集合中的最后一個元素。如果集合為空,則返回 `null`:
collect([1, 2, 3, 4])->last();
// 4
<a name="method-macro"></a>
#### `macro()` {#collection-method}
靜態 `macro` 方法允許你在運行時將方法添加至 `Collection` 類。關于更多信息,請參閱 [擴展集合](#extending-collections) 的文檔。
<a name="method-make"></a>
#### `make()` {#collection-method}
靜態 `make` 方法可以創建一個新的集合實例。請參閱 [創建集合](#creating-collections) 部分。
<a name="method-map"></a>
#### `map()` {#collection-method}
`map` 方法遍歷集合并將每一個值傳入給定的回調函數。該回調函數可以任意修改集合項并返回,從而生成被修改過集合項的新集合:
$collection = collect([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]
> {note} 與其它大多數集合方法一樣,`map` 會返回一個新的集合實例;它不會修改原集合。如果你想修改原集合,請使用 [`transform`](#method-transform) 方法。
<a name="method-mapinto"></a>
#### `mapInto()` {#collection-method}
`mapInto()` 方法可以迭代集合,通過將值傳遞給構造函數來創建給定類的新實例:
class Currency
{
/**
* Create a new currency instance.
*
* @param string $code
* @return void
*/
function __construct(string $code)
{
$this->code = $code;
}
}
$collection = collect(['USD', 'EUR', 'GBP']);
$currencies = $collection->mapInto(Currency::class);
$currencies->all();
// [Currency('USD'), Currency('EUR'), Currency('GBP')]
<a name="method-mapspread"></a>
#### `mapSpread()` {#collection-method}
`mapSpread` 方法可以遍歷集合項,將每個嵌套項值給指定的回調函數。該回調函數可以自由修改該集合項并返回,從而生成被修改過集合項的新集合:
$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunks = $collection->chunk(2);
$sequence = $chunks->mapSpread(function ($even, $odd) {
return $even + $odd;
});
$sequence->all();
// [1, 5, 9, 13, 17]
<a name="method-maptogroups"></a>
#### `mapToGroups()` {#collection-method}
`mapToGroups` 方法通過給定的回調函數對集合項進行分組。該回調函數應該返回一個包含單個鍵 / 值對的關聯數組,從而生成一個分組值的新集合:
$collection = collect([
[
'name' => 'John Doe',
'department' => 'Sales',
],
[
'name' => 'Jane Doe',
'department' => 'Sales',
],
[
'name' => 'Johnny Doe',
'department' => 'Marketing',
]
]);
$grouped = $collection->mapToGroups(function ($item, $key) {
return [$item['department'] => $item['name']];
});
$grouped->toArray();
/*
[
'Sales' => ['John Doe', 'Jane Doe'],
'Marketing' => ['Johnny Doe'],
]
*/
$grouped->get('Sales')->all();
// ['John Doe', 'Jane Doe']
<a name="method-mapwithkeys"></a>
#### `mapWithKeys()` {#collection-method}
`mapWithKeys` 方法遍歷集合并將每個值傳入給定的回調函數。該回調函數將返回一個包含單個鍵 / 值對的關聯數組:
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john@example.com'
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane@example.com'
]
]);
$keyed = $collection->mapWithKeys(function ($item) {
return [$item['email'] => $item['name']];
});
$keyed->all();
/*
[
'john@example.com' => 'John',
'jane@example.com' => 'Jane',
]
*/
<a name="method-max"></a>
#### `max()` {#collection-method}
`max` 方法返回指定鍵的最大值:
$max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
// 20
$max = collect([1, 2, 3, 4, 5])->max();
// 5
<a name="method-median"></a>
#### `median()` {#collection-method}
`median` 方法返回指定鍵的 [中值](https://en.wikipedia.org/wiki/Median):
$median = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');
// 15
$median = collect([1, 1, 2, 4])->median();
// 1.5
<a name="method-merge"></a>
#### `merge()` {#collection-method}
`merge` 方法將合并指定的數組或集合到原集合。如果給定的集合項的字符串鍵與原集合中的字符串鍵相匹配,則指定集合項的值將覆蓋原集合的值:
$collection = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'price' => 200, 'discount' => false]
如果指定的集合項的鍵是數字,這些值將會追加到集合的末尾:
$collection = collect(['Desk', 'Chair']);
$merged = $collection->merge(['Bookcase', 'Door']);
$merged->all();
// ['Desk', 'Chair', 'Bookcase', 'Door']
<a name="method-min"></a>
#### `min()` {#collection-method}
`min` 方法返回指定鍵的最小值:
$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
// 10
$min = collect([1, 2, 3, 4, 5])->min();
// 1
<a name="method-mode"></a>
#### `mode()` {#collection-method}
`mode` 方法返回指定鍵的 [眾數](https://en.wikipedia.org/wiki/Mode_(statistics)) :
$mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');
// [10]
$mode = collect([1, 1, 2, 4])->mode();
// [1]
<a name="method-nth"></a>
#### `nth()` {#collection-method}
`nth` 方法創建由每隔 n 個元素組成的一個新集合:
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->nth(4);
// ['a', 'e']
你可以選擇傳入一個偏移位置作為第二個參數:
$collection->nth(4, 1);
// ['b', 'f']
<a name="method-only"></a>
#### `only()` {#collection-method}
`only` 方法返回集合中所有指定鍵的集合項:
$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
$filtered = $collection->only(['product_id', 'name']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']
與 `only` 對應的是 [except](#method-except) 方法。
<a name="method-pad"></a>
#### `pad()` {#collection-method}
`pad` 方法將使用給定的值填充數組,直到數組達到指定的大小。該方法的行為與 [array_pad](https://secure.php.net/manual/en/function.array-pad.php) PHP 函數功能類似。
要填充到左側,你應該使用負值。如果給定大小的絕對值小于或等于數組的長度,則不會發生填充:
$collection = collect(['A', 'B', 'C']);
$filtered = $collection->pad(5, 0);
$filtered->all();
// ['A', 'B', 'C', 0, 0]
$filtered = $collection->pad(-5, 0);
$filtered->all();
// [0, 0, 'A', 'B', 'C']
<a name="method-partition"></a>
#### `partition()` {#collection-method}
`partition` 方法可以和 PHP 函數中的 `list` 結合使用,用來分開通過指定條件的元素以及那些不通過指定條件的元素:
$collection = collect([1, 2, 3, 4, 5, 6]);
list($underThree, $equalOrAboveThree) = $collection->partition(function ($i) {
return $i < 3;
});
$underThree->all();
// [1, 2]
$equalOrAboveThree->all();
// [3, 4, 5, 6]
<a name="method-pipe"></a>
#### `pipe()` {#collection-method}
`pipe` 方法將集合傳給指定的回調函數并返回結果:
$collection = collect([1, 2, 3]);
$piped = $collection->pipe(function ($collection) {
return $collection->sum();
});
// 6
<a name="method-pluck"></a>
#### `pluck()` {#collection-method}
`pluck` 方法可以獲取集合中指定鍵對應的所有值:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
你也可以通過傳入第二個參數來指定生成集合的鍵:
$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
如果存在重復的鍵,則最后一個匹配元素將被插入到彈出的集合中:
$collection = collect([
['brand' => 'Tesla', 'color' => 'red'],
['brand' => 'Pagani', 'color' => 'white'],
['brand' => 'Tesla', 'color' => 'black'],
['brand' => 'Pagani', 'color' => 'orange'],
]);
$plucked = $collection->pluck('color', 'brand');
$plucked->all();
// ['Tesla' => 'black', 'Pagani' => 'orange']
<a name="method-pop"></a>
#### `pop()` {#collection-method}
`pop` 方法從集合中移除并返回最后一個集合項:
$collection = collect([1, 2, 3, 4, 5]);
$collection->pop();
// 5
$collection->all();
// [1, 2, 3, 4]
<a name="method-prepend"></a>
#### `prepend()` {#collection-method}
`prepend` 方法將指定的值添加的集合的開頭:
$collection = collect([1, 2, 3, 4, 5]);
$collection->prepend(0);
$collection->all();
// [0, 1, 2, 3, 4, 5]
你也可以傳遞第二個參數來設置新增加集合項的鍵:
$collection = collect(['one' => 1, 'two' => 2]);
$collection->prepend(0, 'zero');
$collection->all();
// ['zero' => 0, 'one' => 1, 'two' => 2]
<a name="method-pull"></a>
#### `pull()` {#collection-method}
`pull` 方法把指定鍵對應的值從集合中移除并返回:
$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);
$collection->pull('name');
// 'Desk'
$collection->all();
// ['product_id' => 'prod-100']
<a name="method-push"></a>
#### `push()` {#collection-method}
`push` 方法把指定的值追加到集合項的末尾:
$collection = collect([1, 2, 3, 4]);
$collection->push(5);
$collection->all();
// [1, 2, 3, 4, 5]
<a name="method-put"></a>
#### `put()` {#collection-method}
`put` 方法在集合內設置給定的鍵值對:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->put('price', 100);
$collection->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
<a name="method-random"></a>
#### `random()` {#collection-method}
`random` 方法從集合中返回一個隨機項:
$collection = collect([1, 2, 3, 4, 5]);
$collection->random();
// 4 - (retrieved randomly)
你可以選擇傳入一個整數到 `random` 來指定要獲取的隨即項的數量。只要你顯示傳遞你希望接收的數量時,則會返回項目的集合:
$random = $collection->random(3);
$random->all();
// [2, 4, 5] - (retrieved randomly)
如果集合的項小于指定的數量,則該方法將拋出 `InvalidArgumentException`。
<a name="method-reduce"></a>
#### `reduce()` {#collection-method}
`reduce` 方法將每次迭代的結果傳遞給下一次迭代直到集合減少為單個值:
$collection = collect([1, 2, 3]);
$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
});
// 6
第一次迭代時 `$carry` 的數值為 `null`; however,你也可以通過傳入第二個參數到 `reduce` 來指定它的初始值:
$collection->reduce(function ($carry, $item) {
return $carry + $item;
}, 4);
// 10
<a name="method-reject"></a>
#### `reject()` {#collection-method}
`reject` 方法使用指定的回調函數過濾集合。如果回調函數返回 `true` 就會把對應的集合項從集合中移除:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->reject(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// [1, 2]
與 `reject` 方法對應的是 [`filter`](#method-filter) 方法。
<a name="method-reverse"></a>
#### `reverse()` {#collection-method}
`reverse` 方法用來倒轉集合項的順序,并保留原始的鍵:
$collection = collect(['a', 'b', 'c', 'd', 'e']);
$reversed = $collection->reverse();
$reversed->all();
/*
[
4 => 'e',
3 => 'd',
2 => 'c',
1 => 'b',
0 => 'a',
]
*/
<a name="method-search"></a>
#### `search()` {#collection-method}
`search` 方法在集合中搜索給定的值并返回它的鍵。如果沒有找到,則返回 `false` 。
$collection = collect([2, 4, 6, 8]);
$collection->search(4);
// 1
使用 「寬松」的方式進行搜索,這意味著具有整數值的字符串會被認為等于相同值的整數。使用 「嚴格」的方式進行搜索,就傳入 `true` 作為該方法的第二個參數:
$collection->search('4', true);
// false
或者,你可以通過傳遞回調函數來搜索通過條件測試的第一個集合項:
$collection->search(function ($item, $key) {
return $item > 5;
});
// 2
<a name="method-shift"></a>
#### `shift()` {#collection-method}
`shift` 方法移除并返回集合的第一個集合項:
$collection = collect([1, 2, 3, 4, 5]);
$collection->shift();
// 1
$collection->all();
// [2, 3, 4, 5]
<a name="method-shuffle"></a>
#### `shuffle()` {#collection-method}
`shuffle` 方法隨機打亂集合項:
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] - (generated randomly)
<a name="method-slice"></a>
#### `slice()` {#collection-method}
`slice` 方法返回集合中給定索引開始后面的部分:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4);
$slice->all();
// [5, 6, 7, 8, 9, 10]
如果你想限制返回內容的大小,可以將你期望的大小作為第二個參數傳遞到該方法:
$slice = $collection->slice(4, 2);
$slice->all();
// [5, 6]
默認情況下,返回的內容將會保留原始鍵。如果你不希望保留原始鍵,你可以使用 [`values`](#method-values) 方法來重新建立索引。
<a name="method-some"></a>
#### `some()` {#collection-method}
[`contains`](#method-contains) 方法的別名。
<a name="method-sort"></a>
#### `sort()` {#collection-method}
`sort` 方法對集合進行排序。排序后的集合會保留原數組的鍵,所以在這個例子我們將使用 [`values`](#method-values) 方法去把鍵重置為連續編號的索引:
$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]
如果你有更高級的排序需求,可以通過自己的算法將回調函數傳遞到 `sort` 。請參閱 PHP 文檔的 [`uasort`](https://secure.php.net/manual/en/function.uasort.php#refsect1-function.uasort-parameters) ,這是集合的 `sort` 方法在底層所調用的。
> {tip} 如果你需要對嵌套數組或對象進行排序,請參照 [`sortBy`](#method-sortby) 和 [`sortByDesc`](#method-sortbydesc) 方法。
<a name="method-sortby"></a>
#### `sortBy()` {#collection-method}
`sortBy` 方法將根據指定鍵對集合進行排序。排序后的集合會保留原始數組的鍵,所以在這個例子中我們使用 [`values`](#method-values) 方法將鍵重置為連續編號的索引:
$collection = collect([
['name' => 'Desk', 'price' => 200],
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
]);
$sorted = $collection->sortBy('price');
$sorted->values()->all();
/*
[
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
['name' => 'Desk', 'price' => 200],
]
*/
你也可以傳遞你自己的回調函數用于決定如何對集合的值進行排序:
$collection = collect([
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$sorted = $collection->sortBy(function ($product, $key) {
return count($product['colors']);
});
$sorted->values()->all();
/*
[
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]
*/
<a name="method-sortbydesc"></a>
#### `sortByDesc()` {#collection-method}
該方法與 [`sortBy`](#method-sortby) 方法一樣,但是會以相反的順序來對集合進行排序。
<a name="method-sortkeys"></a>
#### `sortKeys()` {#collection-method}
`sortKeys` 方法通過底層關聯數組的鍵來對集合進行排序:
$collection = collect([
'id' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeys();
$sorted->all();
/*
[
'first' => 'John',
'id' => 22345,
'last' => 'Doe',
]
*/
<a name="method-sortkeysdesc"></a>
#### `sortKeysDesc()` {#collection-method}
該方法與 [`sortKeys`](#method-sortkeys) 方法一樣,但是會以相反的順序來對集合進行排序。
<a name="method-splice"></a>
#### `splice()` {#collection-method}
`splice` 方法移除并返回指定索引開始的集合項片段:
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2);
$chunk->all();
// [3, 4, 5]
$collection->all();
// [1, 2]
你可以傳遞第二個參數用以限制被刪除內容的大小:
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 4, 5]
此外,你可以傳入含有新參數項的第三個參數來代替集合中刪除的集合項:
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1, [10, 11]);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 10, 11, 4, 5]
<a name="method-split"></a>
#### `split()` {#collection-method}
`split` 方法將集合按照給定的值拆分:
$collection = collect([1, 2, 3, 4, 5]);
$groups = $collection->split(3);
$groups->toArray();
// [[1, 2], [3, 4], [5]]
<a name="method-sum"></a>
#### `sum()` {#collection-method}
`sum` 方法返回集合內所有項的和:
collect([1, 2, 3, 4, 5])->sum();
// 15
如果集合包含嵌套數組或對象,則應該傳入一個鍵來指定要進行求和的值:
$collection = collect([
['name' => 'JavaScript: The Good Parts', 'pages' => 176],
['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);
$collection->sum('pages');
// 1272
另外,你可以傳入自己的回調函數來決定要用集合中的哪些值進行求和:
$collection = collect([
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$collection->sum(function ($product) {
return count($product['colors']);
});
// 6
<a name="method-take"></a>
#### `take()` {#collection-method}
`take` 方法返回給定數量項的新集合:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]
你也可以傳遞負整數從集合末尾獲取指定數量的項:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(-2);
$chunk->all();
// [4, 5]
<a name="method-tap"></a>
#### `tap()` {#collection-method}
`tap` 方法將給定的回調函數傳入該集合,允許你在一個特定點「tap」集合,并在不影響集合本身的情況下對集合項執行某些操作:
collect([2, 4, 3, 1, 5])
->sort()
->tap(function ($collection) {
Log::debug('Values after sorting', $collection->values()->toArray());
})
->shift();
// 1
<a name="method-times"></a>
#### `times()` {#collection-method}
靜態 `times` 方法通過調用給定次數的回調函數來創建新集合:
$collection = Collection::times(10, function ($number) {
return $number * 9;
});
$collection->all();
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
使用這個方法可以與工廠結合使用創建出 [Eloquent](/docs/{{version}}/eloquent) 模型:
$categories = Collection::times(3, function ($number) {
return factory(Category::class)->create(['name' => "Category No. $number"]);
});
$categories->all();
/*
[
['id' => 1, 'name' => 'Category #1'],
['id' => 2, 'name' => 'Category #2'],
['id' => 3, 'name' => 'Category #3'],
]
*/
<a name="method-toarray"></a>
#### `toArray()` {#collection-method}
`toArray` 方法將集合轉換成 PHP `數組` 。如果集合的值是 [Eloquent](/docs/{{version}}/eloquent) 模型,那也會被轉換成數組:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/
> {note} `toArray` 也會將所有集合的嵌套對象轉換為數組。如果你想獲取原數組,可以使用 [`all`](#method-all) 方法。
<a name="method-tojson"></a>
#### `toJson()` {#collection-method}
`toJson` 方法將集合轉換成 JSON 字符串:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toJson();
// '{"name":"Desk", "price":200}'
<a name="method-transform"></a>
#### `transform()` {#collection-method}
`transform` 方法迭代集合并對每一個集合項調用給定的回調函數。而集合的內容也會被回調函數的返回值所取代:
$collection = collect([1, 2, 3, 4, 5]);
$collection->transform(function ($item, $key) {
return $item * 2;
});
$collection->all();
// [2, 4, 6, 8, 10]
> {note} 與大多數集合方法不同, `transform` 會修改集合本身。如果你想創建新集合,可以使用 [`map`](#method-map) 方法。
<a name="method-union"></a>
#### `union()` {#collection-method}
`union` 方法將給定的數組添加到集合。如果給定的數組含有與原集合一樣的鍵,則原集合的值不會被改變:
$collection = collect([1 => ['a'], 2 => ['b']]);
$union = $collection->union([3 => ['c'], 1 => ['b']]);
$union->all();
// [1 => ['a'], 2 => ['b'], 3 => ['c']]
<a name="method-unique"></a>
#### `unique()` {#collection-method}
`unique` 方法返回集合中所有唯一項。返回的集合保留著原數組的鍵,所以在這個例子中,我們使用 [`values`](#method-values) 方法把鍵重置為連續編號的索引:
$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
在處理嵌套數組或對象時,你可以指定用于確定唯一性的鍵:
$collection = collect([
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);
$unique = $collection->unique('brand');
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
]
*/
你也可以通過傳遞自己的回調函數來確定項的唯一性:
$unique = $collection->unique(function ($item) {
return $item['brand'].$item['type'];
});
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]
*/
`unique` 方法在檢查項目值時使用「寬松」模式比較,意味著具有整數值的字符串將被視為等于相同值的整數。你可以使用 [`uniqueStrict`](#method-uniquestrict) 方法做「嚴格」模式比較。
<a name="method-uniquestrict"></a>
#### `uniqueStrict()` {#collection-method}
這個方法與 [`unique`](#method-unique) 方法一樣,然而,所有的值是用 「嚴格」模式來比較的。
<a name="method-unless"></a>
#### `unless()` {#collection-method}
`unless` 方法當傳入的第一個參數不為 `true` 的時候,將執行給定的回調函數:
$collection = collect([1, 2, 3]);
$collection->unless(true, function ($collection) {
return $collection->push(4);
});
$collection->unless(false, function ($collection) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 5]
與 `unless` 對應的是 [`when`](#method-when) 方法。
<a name="method-unlessempty"></a>
#### `unlessEmpty()` {#collection-method}
[`whenNotEmpty`](#method-whennotempty) 方法的別名。
<a name="method-unlessnotempty"></a>
#### `unlessNotEmpty()` {#collection-method}
[`whenEmpty`](#method-whenempty) 方法的別名。
<a name="method-unwrap"></a>
#### `unwrap()` {#collection-method}
靜態 `unwrap` 方法返回集合內部的可用值:
Collection::unwrap(collect('John Doe'));
// ['John Doe']
Collection::unwrap(['John Doe']);
// ['John Doe']
Collection::unwrap('John Doe');
// 'John Doe'
<a name="method-values"></a>
#### `values()` {#collection-method}
`values` 方法返回鍵被重置為連續編號的新集合:
$collection = collect([
10 => ['product' => 'Desk', 'price' => 200],
11 => ['product' => 'Desk', 'price' => 200]
]);
$values = $collection->values();
$values->all();
/*
[
0 => ['product' => 'Desk', 'price' => 200],
1 => ['product' => 'Desk', 'price' => 200],
]
*/
<a name="method-when"></a>
#### `when()` {#collection-method}
`when` 方法當傳入的第一個參數為 `true` 時,將執行給定的回調函數:
$collection = collect([1, 2, 3]);
$collection->when(true, function ($collection) {
return $collection->push(4);
});
$collection->when(false, function ($collection) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 4]
與 `when` 對應的是 [`unless`](#method-unless) 方法。
<a name="method-whenempty"></a>
#### `whenEmpty()` {#collection-method}
`whenEmpty` 方法當集合為空時,將執行給定的回調函數:
$collection = collect(['michael', 'tom']);
$collection->whenEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// ['michael', 'tom']
$collection = collect();
$collection->whenEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// ['adam']
$collection = collect(['michael', 'tom']);
$collection->whenEmpty(function($collection) {
return $collection->push('adam');
}, function($collection) {
return $collection->push('taylor');
});
$collection->all();
// ['michael', 'tom', 'taylor']
與 `whenEmpty` 對應的是 [`whenNotEmpty`](#method-whennotempty) 方法。
<a name="method-whennotempty"></a>
#### `whenNotEmpty()` {#collection-method}
`whenNotEmpty` 方法當集合不為空時,將執行給定的回調函數:
$collection = collect(['michael', 'tom']);
$collection->whenNotEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// ['michael', 'tom', 'adam']
$collection = collect();
$collection->whenNotEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// []
$collection = collect();
$collection->whenNotEmpty(function($collection) {
return $collection->push('adam');
}, function($collection) {
return $collection->push('taylor');
});
$collection->all();
// ['taylor']
與 `whenNotEmpty` 對應的是 [`whenEmpty`](#method-whenempty) 方法。
<a name="method-where"></a>
#### `where()` {#collection-method}
`where` 方法通過給定的鍵 / 值對過濾集合:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->where('price', 100);
$filtered->all();
/*
[
['product' => 'Chair', 'price' => 100],
['product' => 'Door', 'price' => 100],
]
*/
`where` 方法在檢查集合項值時使用「寬松」模式比較,這意味著具有整數值的字符串會被認為等于相同值的整數。你可以使用 [`whereStrict`](#method-wherestrict) 方法進行「嚴格」模式比較。
<a name="method-wherestrict"></a>
#### `whereStrict()` {#collection-method}
這個方法與 [`where`](#method-where) 方法類似;不同的是會用「嚴格」的模式比較。
<a name="method-wherebetween"></a>
#### `whereBetween()` {#collection-method}
`whereBetween` 方法會用給定的范圍對集合進行過濾:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 80],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Pencil', 'price' => 30],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereBetween('price', [100, 200]);
$filtered->all();
/*
[
['product' => 'Desk', 'price' => 200],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]
*/
<a name="method-wherein"></a>
#### `whereIn()` {#collection-method}
`whereIn` 會根據包含給定數組的鍵 / 值對來過濾集合:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereIn('price', [150, 200]);
$filtered->all();
/*
[
['product' => 'Bookcase', 'price' => 150],
['product' => 'Desk', 'price' => 200],
]
*/
`whereIn` 方法使用「寬松」的比較來檢查集合項的值,這意味著具有整數值的字符串會被視為等于相同值的整數。你可以使用 [`whereInStrict`](#method-whereinstrict) 方法進行「嚴格」模式比較。
<a name="method-whereinstrict"></a>
#### `whereInStrict()` {#collection-method}
這個方法與 [`whereIn`](#method-wherein) 方法類似;不同的是會使用「嚴格」模式進行比較。
<a name="method-whereinstanceof"></a>
#### `whereInstanceOf()` {#collection-method}
`whereInstanceOf` 方法根據指定的類來過濾集合:
$collection = collect([
new User,
new User,
new Post,
]);
return $collection->whereInstanceOf(User::class);
<a name="method-wherenotbetween"></a>
#### `whereNotBetween()` {#collection-method}
`whereNotBetween` 方法在指定的范圍內過濾集合:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 80],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Pencil', 'price' => 30],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereNotBetween('price', [100, 200]);
$filtered->all();
/*
[
['product' => 'Chair', 'price' => 80],
['product' => 'Pencil', 'price' => 30],
]
*/
<a name="method-wherenotin"></a>
#### `whereNotIn()` {#collection-method}
`whereNotIn` 方法根據通過指定的鍵和不含有指定數組的值來對集合進行過濾:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereNotIn('price', [150, 200]);
$filtered->all();
/*
[
['product' => 'Chair', 'price' => 100],
['product' => 'Door', 'price' => 100],
]
*/
`whereNotIn` 方法使用「寬松」模式比較來檢查集合項的值,這意味著具有整數值的字符串將被視為等于相同值的整數。你可以使用 [`whereNotInStrict`](#method-wherenotinstrict) 方法做 「嚴格」模式比較。
<a name="method-wherenotinstrict"></a>
#### `whereNotInStrict()` {#collection-method}
這個方法與 [`whereNotIn`](#method-wherenotin) 方法類似;不同的是會使用 「嚴格」模式作比較。
<a name="method-wrap"></a>
#### `wrap()` {#collection-method}
靜態 `wrap` 方法在適當的情況下將指定的值放在集合中:
$collection = Collection::wrap('John Doe');
$collection->all();
// ['John Doe']
$collection = Collection::wrap(['John Doe']);
$collection->all();
// ['John Doe']
$collection = Collection::wrap(collect('John Doe'));
$collection->all();
// ['John Doe']
<a name="method-zip"></a>
#### `zip()` {#collection-method}
`zip` 方法將指定數組的值和相應索引的原集合的值合并在一起:
$collection = collect(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]
<a name="higher-order-messages"></a>
## 高階消息傳遞
集合也提供對「高階消息傳遞」的支持,即集合常見操作的快捷方式。支持高階消息傳遞的集合方法有: [`average`](#method-average), [`avg`](#method-avg), [`contains`](#method-contains), [`each`](#method-each), [`every`](#method-every), [`filter`](#method-filter), [`first`](#method-first), [`flatMap`](#method-flatmap), [`groupBy`](#method-groupby), [`keyBy`](#method-keyby), [`map`](#method-map), [`max`](#method-max), [`min`](#method-min), [`partition`](#method-partition), [`reject`](#method-reject), [`some`](#method-some), [`sortBy`](#method-sortby), [`sortByDesc`](#method-sortbydesc), [`sum`](#method-sum), and [`unique`](#method-unique)。
每個高階消息傳遞都能作為集合實例的動態的屬性來訪問。例如,使用 `each` 高階消息傳遞在集合中的每個對象上調用一個方法:
$users = User::where('votes', '>', 500)->get();
$users->each->markAsVip();
同樣,我們可以使用 `sum` 高階消息傳遞來收集 users 集合中的「投票」總數:
$users = User::where('group', 'Development')->get();
return $users->sum->votes;
- 入門指南
- 安裝
- 部署
- 基礎功能
- 路由
- 中間件
- CSRF 保護
- 控制器
- 請求
- 響應
- 視圖
- URL
- Session
- 表單驗證
- 錯誤
- 日志
- 前端開發
- Blade 模板
- 本地化
- 腳手架
- 編譯資源 Mix
- 安全相關
- 用戶認證
- API 認證
- 綜合話題
- 命令行
- 廣播
- 緩存
- 集合
- 事件
- 文件存儲
- 輔助函數
- 郵件發送
- 消息通知
- 擴展包開發
- 隊列
- 任務調度
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- Redis
- Eloquent ORM
- 快速入門
- 速查表
- Artisan
- Auth
- Blade
- Cache
- Collection
- Composer
- Config
- Container
- Cookie
- DB
- Environment
- Event
- File
- Helper
- Input
- Lang
- Log
- Model
- Pagination
- Queue
- Redirect
- Request
- Response
- Route
- SSH
- Schema
- Security
- Session
- Storage
- String
- URL
- UnitTest
- Validation
- View