* * * * *
[TOC]
## 簡介
`Illuminate\Support\Collection`?類提供了一個更具可讀性的、更便于處理數組數據的封裝。具體例子看下面的代碼。我們使用了?`collect`?函數從數組中創建新的集合實例,對其中的每個元素運行?`strtoupper`?函數之后再移除所有的空元素:
~~~
$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
return strtoupper($name);
})
->reject(function ($name) {
return empty($name);
});
~~~
正如你看到的,`Collection`?類允許你鏈式調用其方法,以達到在底層數組上優雅地執行 map 和 reject 操作。一般來說,集合是不可改變的,這意味著每個?`Collection`?方法都會返回一個全新的?`Collection`?實例。
### 創建集合
如上所述,輔助函數?`collect`?會為給定的數組返回一個新的?`Illuminate\Support\Collection`?實例。所以,創建一個集合就這么簡單:
~~~
$collection = collect([1, 2, 3]);
~~~
> {tip} 默認情況下,[Eloquent](http://www.hmoore.net/tonyyu/laravel_5_6/786272)?查詢的結果返回的內容都是?`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']
~~~
通常,你應該在?[服務提供者](http://www.hmoore.net/tonyyu/laravel_5_6/786057)?中聲明集合宏。
## 可用方法
這個文檔接下來的內容,我們會探討?`Collection`?類每個可用的方法。記住,所有方法都可以以鏈式訪問的形式優雅地操縱數組。而且,幾乎所有的方法都會返回新的?`Collection`?實例,允許你在必要時保存集合的原始副本。
[all](#all_155)
[average](#average_165)
[avg](#avg_169)
[chunk](#chunk_183)
[collapse](#collapse_209)
[combine](#combine_223)
[concat](#concat_237)
[contains](#contains_251)
[containsStrict](#containsStrict_294)
[count](#count_298)
[crossJoin](#crossJoin_310)
[dd](#dd_350)
[diff](#diff_371)
[diffAssoc](#diffAssoc_385)
[diffKeys](#diffKeys_408)
[dump](#dump_433)
[each](#each_454)
[eachSpread](#eachSpread_474)
[every](#every_494)
[except](#except_506)
[filter](#filter_522)
[first](#first_550)
[firstWhere](#firstWhere_570)
[flatMap](#flatMap_595)
[flatten](#flatten_615)
[flip](#flip_655)
[forget](#forget_669)
[forPage](#forPage_685)
[get](#get_699)
[groupBy](#groupBy_731)
[has](#has_824)
[implode](#implode_836)
[intersect](#intersect_859)
[intersectByKeys](#intersectByKeys_873)
[isEmpty](#isEmpty_891)
[isNotEmpty](#isNotEmpty_901)
[keyBy](#keyBy_911)
[keys](#keys_950)
[last](#last_967)
[macro](#macro_987)
[make](#make_991)
[map](#map_995)
[mapInto](#mapInto_1013)
[mapSpread](#mapSpread_1041)
[mapToGroups](#mapToGroups_1059)
[mapWithKeys](#mapWithKeys_1097)
[max](#max_1129)
[median](#median_1143)
[merge](#merge_1157)
[min](#min_1183)
[mode](#mode_1197)
[nth](#nth_1211)
[only](#only_1231)
[pad](#pad_1247)
[partition](#partition_1269)
[pipe](#pipe_1281)
[pluck](#pluck_1295)
[pop](#pop_1339)
[prepend](#prepend_1355)
[pull](#pull_1381)
[push](#push_1397)
[put](#put_1411)
[random](#random_1425)
[reduce](#reduce_1447)
[reject](#reject_1471)
[reverse](#reverse_1489)
[search](#search_1511)
[shift](#shift_1541)
[shuffle](#shuffle_1557)
[slice](#slice_1571)
[sort](#sort_1597)
[sortBy](#sortBy_1615)
[sortByDesc](#sortByDesc_1663)
[sortKeys](#sortKeys_1667)
[sortKeysDesc](#sortKeysDesc_1691)
[splice](#splice_1695)
[split](#split_1745)
[sum](#sum_1759)
[take](#take_1798)
[tap](#tap_1824)
[times](#times_1839)
[toArray](#toArray_1871)
[toJson](#toJson_1889)
[transform](#transform_1901)
[union](#union_1919)
[unique](#unique_1933)
[uniqueStrict](#uniqueStrict_1991)
[unless](#unless_1995)
[unwrap](#unwrap_2017)
[values](#values_2035)
[when](#when_2057)
[where](#where_2079)
[whereStrict](#whereStrict_2105)
[whereIn](#whereIn_2109)
[whereInStrict](#whereInStrict_2135)
[whereNotIn](#whereNotIn_2139)
[whereNotInStrict](#whereNotInStrict_2165)
[wrap](#wrap_2169)
[zip](#zip_2193)
## 方法清單
#### `all()`
`all`?方法返回集合表示的底層數組:
~~~
collect([1, 2, 3])->all();
// [1, 2, 3]
~~~
#### `average()`
[`avg`](#avg_169)?方法的別名。
#### `avg()`
`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
~~~
#### `chunk()`
`chunk`?方法將集合拆成多個指定大小的小集合:
~~~
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
~~~
這個方法特別適用在使用柵格系統時的?[視圖](http://www.hmoore.net/tonyyu/laravel_5_6/786178),比如?[Bootstrap](https://getbootstrap.com/css/#grid)。想像你有一個?[Eloquent](http://www.hmoore.net/tonyyu/laravel_5_6/786272)?模型的集合要在柵格中顯示:
~~~
@foreach ($products->chunk(3) as $chunk)
<div class="row">
@foreach ($chunk as $product)
<div class="col-xs-4">{{ $product->name }}</div>
@endforeach
</div>
@endforeach
~~~
#### `collapse()`
`collapse`?方法將多個數組的集合合并成一個數組的集合:
~~~
$collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
$collapsed = $collection->collapse();
$collapsed->all();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
~~~
#### `combine()`
`combine`?方法可以將一個集合的值作為「鍵」,再將另一個數組或者集合的值作為「值」合并成一個集合:
~~~
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]
~~~
#### `concat()`
`concat`?方法將給定的?`array`?或集合值附加到集合的末尾:
~~~
$collection = collect(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
$concatenated->all();
// ['John Doe', 'Jane Doe', 'Johnny Doe']
~~~
#### `contains()`
`contains`?方法判斷集合是否包含給定的項目:
~~~
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->contains('Desk');
// true
$collection->contains('New York');
// false
~~~
你也可以用?`contains`?方法匹配一對鍵/值,即判斷給定的配對是否存在于集合中:
~~~
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->contains('product', 'Bookcase');
// false
~~~
最后,你也可以傳遞一個回調到?`contains`?方法來執行自己的真實測試:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$collection->contains(function ($value, $key) {
return $value > 5;
});
// false
~~~
`contains`?方法在檢查項目值時使用「寬松」比較,意味著具有整數值的字符串將被視為等于相同值的整數。 相反?`containsStrict`?方法則是使用「嚴格」比較進行過濾。
#### `containsStrict()`
此方法和?[`contains`](#contains_251)?方法類似,但是它卻是使用了「嚴格」比較來比較所有值。
#### `count()`
`count`?方法返回該集合內的項目總數:
~~~
$collection = collect([1, 2, 3, 4]);
$collection->count();
// 4
~~~
#### `crossJoin()`
`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'],
]
*/
~~~
#### `dd()`
`dd`?方法轉儲集合的項目并結束腳本的執行:
~~~
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/
~~~
如果您不想停止執行腳本,請改用?[`dump`](#dump_433)?方法。
#### `diff()`
`diff`?方法將集合與其它集合或純 PHP 數組進行值的比較,然后返回原集合中存在而給定集合中不存在的值:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]
~~~
#### `diffAssoc()`
`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]
~~~
#### `diffKeys()`
`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]
~~~
#### `dump()`
`dump`?方法將打印集合的每一項:
~~~
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dump();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/
~~~
如果你想打印集合后并停止執行腳本,請改用?[`dd`](dd_350)?方法代替。
#### `each()`
`each`?方法將迭代集合中的內容并將其傳遞到回調函數中:
~~~
$collection = $collection->each(function ($item, $key) {
//
});
~~~
如果你想要中斷對內容的迭代,那就從回調中返回?`false`:
~~~
$collection = $collection->each(function ($item, $key) {
if (/* some condition */) {
return false;
}
});
~~~
#### `eachSpread()`
`eachSpread`?方法迭代集合的項目,將每個嵌套項目值傳遞給給定的回調:
~~~
$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);
$collection->eachSpread(function ($name, $age) {
//
});
~~~
您可以通過從回調中返回?`false`?來停止迭代項目:
~~~
$collection->eachSpread(function ($name, $age) {
return false;
});
~~~
#### `every()`
`every`?方法可用于驗證集合中每一個元素都通過給定的真實測試:
~~~
collect([1, 2, 3, 4])->every(function ($value, $key) {
return $value > 2;
});
// false
~~~
#### `except()`
`except`?方法返回集合中除了指定鍵以外的所有項目:
~~~
$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);
$filtered = $collection->except(['price', 'discount']);
$filtered->all();
// ['product_id' => 1]
~~~
與?`except`?相反的方法,請查看?[only](#only_1231)?方法。
#### `filter()`
`filter`?方法使用給定的回調函數過濾集合的內容,只留下那些通過給定真實測試的內容:
~~~
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// [3, 4]
~~~
如果沒有提供回調函數,集合中所有返回?`false`?的元素都會被移除:
~~~
$collection = collect([1, 2, 3, null, false, '', 0, []]);
$collection->filter()->all();
// [1, 2, 3]
~~~
與?`filter`?相反的方法,可以查看?[reject](#reject_1471)?方法。
#### `first()`
`first`?方法返回集合中通過給定真實測試的第一個元素:
~~~
collect([1, 2, 3, 4])->first(function ($value, $key) {
return $value > 2;
});
// 3
~~~
你也可以不傳入參數使用?`first`?方法以獲取集合中第一個元素。如果集合是空的,則會返回?`null`:
~~~
collect([1, 2, 3, 4])->first();
// 1
~~~
#### `firstWhere()`
`firstWhere`?方法用給定的鍵/值對返回集合中的第一個元素:
~~~
$collection = collect([
['name' => 'Regena', 'age' => 12],
['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]
~~~
#### `flatMap()`
`flatMap`?方法遍歷集合并將其中的每個值傳遞到給定的回調。可以通過回調修改每個值的內容再返回出來,從而形成一個新的被修改過內容的集合。然后你就可以用?`all()`?打印修改后的數組:
~~~
$collection = collect([
['name' => 'Sally'],
['school' => 'Arkansas'],
['age' => 28]
]);
$flattened = $collection->flatMap(function ($values) {
return array_map('strtoupper', $values);
});
$flattened->all();
// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];
~~~
#### `flatten()`
`flatten`?方法將多維集合轉為一維的:
~~~
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['taylor', 'php', 'javascript'];
~~~
你還可以選擇性地傳入「深度」參數:
~~~
$collection = collect([
'Apple' => [
['name' => 'iPhone 6S', 'brand' => 'Apple'],
],
'Samsung' => [
['name' => 'Galaxy S7', 'brand' => 'Samsung']
],
]);
$products = $collection->flatten(1);
$products->values()->all();
/*
[
['name' => 'iPhone 6S', 'brand' => 'Apple'],
['name' => 'Galaxy S7', 'brand' => 'Samsung'],
]
*/
~~~
在這個例子里,調用?`flatten`?方法時不傳入深度參數的話也會將嵌套數組轉成一維的,然后返回 ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']。傳入深度參數能讓你限制設置返回數組的層數。
#### `flip()`
`flip`?方法將集合中的鍵和對應的數值進行互換:
~~~
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$flipped = $collection->flip();
$flipped->all();
// ['taylor' => 'name', 'laravel' => 'framework']
~~~
#### `forget()`
`forget`?方法通過給定的鍵來移除掉集合中對應的內容:
~~~
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$collection->forget('name');
$collection->all();
// ['framework' => 'laravel']
~~~
> {note} 與大多數集合的方法不同,`forget`?不會返回修改過后的新集合;它會直接修改原來的集合。
#### `forPage()`
`forPage`?方法返回給定頁碼上顯示的項目的新集合。這個方法接受頁碼作為其第一個參數和每頁顯示的項目數作為其第二個參數。
~~~
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);
$chunk->all();
// [4, 5, 6]
~~~
#### `get()`
`get`?方法返回給定鍵的項目。如果該鍵不存在,則返回?`null`:
~~~
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('name');
// taylor
~~~
你可以選擇性地傳遞默認值作為第二個參數:
~~~
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('foo', 'default-value');
// default-value
~~~
你甚至可以將回調函數當作默認值。如果指定的鍵不存在,就會返回回調的結果:
~~~
$collection->get('email', function () {
return 'default-value';
});
// default-value
~~~
#### `groupBy()`
`groupBy`?方法根據給定的鍵對集合內的項目進行分組:
~~~
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->toArray();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
~~~
除了傳入一個字符串的「鍵」,你還可以傳入一個回調。該回調應該返回你希望用來分組的鍵的值:
~~~
$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']],
],
],
];
*/
~~~
#### `has()`
`has`?方法判斷集合中是否存在給定的鍵:
~~~
$collection = collect(['account_id' => 1, 'product' => 'Desk']);
$collection->has('product');
// true
~~~
#### `implode()`
`implode`?方法合并集合中的項目。其參數取決于集合中項目的類型。如果集合包含數組或對象,你應該傳入你希望連接的屬性的鍵,以及你希望放在值之間用來「拼接」的字符串:
~~~
$collection = collect([
['account_id' => 1, 'product' => 'Desk'],
['account_id' => 2, 'product' => 'Chair'],
]);
$collection->implode('product', ', ');
// Desk, Chair
~~~
如果集合包含簡單的字符串或數值,只需要傳入「拼接」用的字符串作為該方法的唯一參數即可:
~~~
collect([1, 2, 3, 4, 5])->implode('-');
// '1-2-3-4-5'
~~~
#### `intersect()`
`intersect`?方法從原集合中刪除不在給定「數組」或集合中的任何值。最終的集合會保留原集合的鍵:
~~~
$collection = collect(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']
~~~
#### `intersectByKeys()`
`intersectByKeys`?方法刪除原集合中不存在于給定「數組」或集合中的任何鍵:
~~~
$collection = collect([
'serial' => 'UX301', 'type' => 'screen', 'year' => 2009
]);
$intersect = $collection->intersectByKeys([
'reference' => 'UX404', 'type' => 'tab', 'year' => 2011
]);
$intersect->all();
// ['type' => 'screen', 'year' => 2009]
~~~
#### `isEmpty()`
如果集合是空的,`isEmpty`?方法返回?`true`,否則返回?`false`:
~~~
collect([])->isEmpty();
// true
~~~
#### `isNotEmpty()`
如果集合不是空的,`isNotEmpty`?方法會返回?`true`:否則返回?`false`:
~~~
collect([])->isNotEmpty();
// false
~~~
#### `keyBy()`
`keyBy`?方法以給定的鍵作為集合的鍵。如果多個項目具有相同的鍵,則只有最后一個項目會顯示在新集合中:
~~~
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keyed = $collection->keyBy('product_id');
$keyed->all();
/*
[
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
~~~
你也可以傳入一個回調方法,回調返回的值會作為該集合的鍵:
~~~
$keyed = $collection->keyBy(function ($item) {
return strtoupper($item['product_id']);
});
$keyed->all();
/*
[
'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
~~~
#### `keys()`
`keys`?方法返回集合的所有鍵:
~~~
$collection = collect([
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keys = $collection->keys();
$keys->all();
// ['prod-100', 'prod-200']
~~~
#### `last()`
`last`?方法返回集合中通過給定真相測試的最后一個元素:
~~~
collect([1, 2, 3, 4])->last(function ($value, $key) {
return $value < 3;
});
// 2
~~~
你也可以不傳入參數調用?`last`?方法來獲取集合中最后一個元素。如果集合是空的,返回?`null`:
~~~
collect([1, 2, 3, 4])->last();
// 4
~~~
#### `macro()`
靜態?`macro`?方法允許您在運行時將方法添加到?`Collection`?類。 有關更多信息,請參閱?[擴展集合](http://www.hmoore.net/tonyyu/laravel_5_6/786241#_27)?的文檔。
#### `make()`
靜態?`make`?方法可以創建一個新的集合實例。 請參閱?[創建集合](http://www.hmoore.net/tonyyu/laravel_5_6/786241#_17)?部分。
#### `map()`
`map`?方法遍歷集合并將每一個值傳入給定的回調。該回調可以任意修改項目并返回,從而形成新的被修改過項目的集合:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]
~~~
> {note} 像其它的集合方法一樣,`map`?方法會返回一個新的集合實例;它不會修改它所調用的集合。如果你想改變原集合,請使用?[`transform`](#transform_1901)?方法。
#### `mapInto()`
`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')]
~~~
#### `mapSpread()`
`mapSpread`?方法可以迭代集合的項目,將每個嵌套項目值傳遞給給定的回調函數。 該回調可以自由修改該項目并將其返回,從而形成一個新的修改項目集合:
~~~
$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunks = $collection->chunk(2);
$sequence = $chunks->mapSpread(function ($odd, $even) {
return $odd + $even;
});
$sequence->all();
// [1, 5, 9, 13, 17]
~~~
#### `mapToGroups()`
`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' => ['Johhny Doe'],
]
*/
$grouped->get('Sales')->all();
// ['John Doe', 'Jane Doe']
~~~
#### `mapWithKeys()`
`mapWithKeys`?方法遍歷集合并將每個值傳入給定的回調。回調應該返回包含一個鍵值對的關聯數組:
~~~
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john@example.com'
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane@example.com'
]
]);
$keyed = $collection->mapWithKeys(function ($item) {
return [$item['email'] => $item['name']];
});
$keyed->all();
/*
[
'john@example.com' => 'John',
'jane@example.com' => 'Jane',
]
*/
~~~
#### `max()`
`max`?方法返回給定鍵的最大值:
~~~
$max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
// 20
$max = collect([1, 2, 3, 4, 5])->max();
// 5
~~~
#### `median()`
`median`?方法返回給定鍵的?[中值](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
~~~
#### `merge()`
`merge`?方法將給定數組或集合合并到原集合。如果給定項目中的字符串鍵與原集合中的字符串鍵匹配,給定的項目的值將會覆蓋原集合中的值:
~~~
$collection = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'price' => 200, 'discount' => false]
~~~
如果給定的項目的鍵是數字,這些值將被追加到集合的末尾:
~~~
$collection = collect(['Desk', 'Chair']);
$merged = $collection->merge(['Bookcase', 'Door']);
$merged->all();
// ['Desk', 'Chair', 'Bookcase', 'Door']
~~~
#### `min()`
`min`?方法返回給定鍵的最小值:
~~~
$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
// 10
$min = collect([1, 2, 3, 4, 5])->min();
// 1
~~~
#### `mode()`
`mode`?方法返回給定鍵的?[眾數](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]
~~~
#### `nth()`
`nth`?方法創建由每隔?`n`?個元素組成一個新的集合:
~~~
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->nth(4);
// ['a', 'e']
~~~
你也可以選擇傳入一個偏移位置作為第二個參數
~~~
$collection->nth(4, 1);
// ['b', 'f']
~~~
#### `only()`
`only`?方法返回集合中給定鍵的所有項目:
~~~
$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
$filtered = $collection->only(['product_id', 'name']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']
~~~
與?`only`?相反的方法,請查看?[except](#except_506)?方法。
#### `pad()`
`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']
~~~
#### `partition()`
`partition`?法可以和 PHP 中的?`list`?方法結合使用,來分開通過指定條件的元素以及那些不通過指定條件的元素:
~~~
$collection = collect([1, 2, 3, 4, 5, 6]);
list($underThree, $aboveThree) = $collection->partition(function ($i) {
return $i < 3;
});
~~~
#### `pipe()`
`pipe`?方法將集合傳給給定的回調并返回結果:
~~~
$collection = collect([1, 2, 3]);
$piped = $collection->pipe(function ($collection) {
return $collection->sum();
});
// 6
~~~
#### `pluck()`
`pluck`?方法可以獲取集合中給定鍵對應的所有值:
~~~
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
~~~
你也可以通過傳入第二個參數來指定生成的集合的鍵:
~~~
$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
~~~
如果存在重復鍵,則最后一個匹配元素將被插入到彈出的集合中:
~~~
$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']
~~~
#### `pop()`
`pop`?方法移除并返回集合中的最后一個項目:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$collection->pop();
// 5
$collection->all();
// [1, 2, 3, 4]
~~~
#### `prepend()`
`prepend`?方法將給定的值添加到集合的開頭:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$collection->prepend(0);
$collection->all();
// [0, 1, 2, 3, 4, 5]
~~~
你也可以傳遞第二個參數來設置新增加項的鍵:
~~~
$collection = collect(['one' => 1, 'two' => 2]);
$collection->prepend(0, 'zero');
$collection->all();
// ['zero' => 0, 'one' => 1, 'two' => 2]
~~~
#### `pull()`
`pull`?方法把給定鍵對應的值從集合中移除并返回:
~~~
$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);
$collection->pull('name');
// 'Desk'
$collection->all();
// ['product_id' => 'prod-100']
~~~
#### `push()`
`push`?方法把給定值添加到集合的末尾:
~~~
$collection = collect([1, 2, 3, 4]);
$collection->push(5);
$collection->all();
// [1, 2, 3, 4, 5]
~~~
#### `put()`
`put`?方法在集合內設置給定的鍵值對:
~~~
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->put('price', 100);
$collection->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
~~~
#### `random()`
`random`?方法從集合中返回一個隨機項:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$collection->random();
// 4 - (retrieved randomly)
~~~
你可以選擇性傳入一個整數到?`random`?來指定要獲取的隨機項的數量。只要你顯式傳遞你希望接收的數量時,則會返回項目的集合:
~~~
$random = $collection->random(3);
$random->all();
// [2, 4, 5] - (retrieved randomly)
~~~
#### `reduce()`
`reduce`?方法將每次迭代的結果傳遞給下一次迭代直到集合減少為單個值:
~~~
$collection = collect([1, 2, 3]);
$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
});
// 6
~~~
第一次迭代時?`$carry`?的數值為?`null`;你也可以通過傳入第二個參數到?`reduce`?來指定它的初始值:
~~~
$collection->reduce(function ($carry, $item) {
return $carry + $item;
}, 4);
// 10
~~~
#### `reject()`
`reject`?方法使用指定的回調過濾集合。如果回調返回?`true`?,就會把對應的項目從集合中移除:
~~~
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->reject(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// [1, 2]
~~~
與?`reject`?相反的方法,可以查看?[`filter`](#filter_522)?方法。
#### `reverse()`
`reverse`?方法用來倒轉集合中項目的順序:
~~~
$collection = collect(['a', 'b', 'c', 'd', 'e']);
$reversed = $collection->reverse();
$reversed->all();
/*
[
4 => 'e',
3 => 'd',
2 => 'c',
1 => 'b',
0 => 'a',
]
*/
~~~
#### `search()`
`search`?方法搜索給定的值并返回它的鍵。如果找不到,則返回?`false`:
~~~
$collection = collect([2, 4, 6, 8]);
$collection->search(4);
// 1
~~~
搜索使用「寬松」比較完成,這意味著具有整數值的字符串會被認為等于相同值的整數。要使用「嚴格」比較,就傳入?`true`?作為該方法的第二個參數:
~~~
$collection->search('4', true);
// false
~~~
另外,你可以通過回調來搜索第一個通過真實測試的項目:
~~~
$collection->search(function ($item, $key) {
return $item > 5;
});
// 2
~~~
#### `shift()`
`shift`?方法移除并返回集合的第一個項目:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$collection->shift();
// 1
$collection->all();
// [2, 3, 4, 5]
~~~
#### `shuffle()`
`shuffle`?方法隨機排序集合中的項目:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] - (generated randomly)
~~~
#### `slice()`
`slice`?方法返回集合中給定值后面的部分:
~~~
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4);
$slice->all();
// [5, 6, 7, 8, 9, 10]
~~~
如果你想限制返回內容的大小,就將期望的大小作為第二個參數傳遞給方法:
~~~
$slice = $collection->slice(4, 2);
$slice->all();
// [5, 6]
~~~
默認情況下,返回的內容將會保留原始鍵。假如你不希望保留原始的鍵,你可以使用?[`values`](#values_2035)?方法來重新建立索引。
#### `sort()`
`sort`?方法對集合進行排序。排序后的集合保留著原數組的鍵,所以在這個例子中我們使用?[`values`](#values_2035)?方法來把鍵重置為連續編號的索引:
~~~
$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]
~~~
如果你有更高級的排序需求,你可以傳入回調來用你自己的算法進行排序。請參閱 PHP 文檔的?[`uasort`](https://secure.php.net/manual/en/function.uasort.php#refsect1-function.uasort-parameters),這是集合的?`sort`?方法在底層所調用的
> {tip} 如果要對嵌套數組或對象的集合進行排序,參考?[`sortBy`](#sortBy_1615)?和?[`sortByDesc`](#sortByDesc_1663)?方法。
#### `sortBy()`
`sortBy`?法以給定的鍵對集合進行排序。排序后的集合保留了原數組鍵,所以在這個例子中,我們使用?[`values`](#values_2035)?方法將鍵重置為連續編號的索引:
~~~
$collection = collect([
['name' => 'Desk', 'price' => 200],
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
]);
$sorted = $collection->sortBy('price');
$sorted->values()->all();
/*
[
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
['name' => 'Desk', 'price' => 200],
]
*/
~~~
你還可以傳入自己的回調以決定如何對集合的值進行排序:
~~~
$collection = collect([
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$sorted = $collection->sortBy(function ($product, $key) {
return count($product['colors']);
});
$sorted->values()->all();
/*
[
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]
*/
~~~
#### `sortByDesc()`
這個方法與?[`sortBy`](#sortBy_1615)?方法一樣,但是會以相反的順序來對集合進行排序:
#### `sortKeys()`
`sortKeys`?方法通過底層關聯數組的鍵來排序集合:
~~~
$collection = collect([
'id' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeys();
$sorted->all();
/*
[
'first' => 'John',
'id' => 22345,
'last' => 'Doe',
]
*/
~~~
#### `sortKeysDesc()`
這個方法的用法和?[`sortKeys`](#sortKeys_1667)?方法一樣,區別就是返回的集合是倒序。
#### `splice()`
`splice`?方法刪除并返回從給定值后的內容,原集合也會受到影響:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2);
$chunk->all();
// [3, 4, 5]
$collection->all();
// [1, 2]
~~~
你可以傳入第二個參數以限制被刪除內容的大小:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 4, 5]
~~~
此外,你可以傳入含有新項目的第三個參數來代替集合中刪除的項目:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1, [10, 11]);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 10, 11, 4, 5]
~~~
#### `split()`
`split`?方法將集合按給定的值拆分:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$groups = $collection->split(3);
$groups->toArray();
// [[1, 2], [3, 4], [5]]
~~~
#### `sum()`
`sum`?方法返回集合內所有項目的總和:
~~~
collect([1, 2, 3, 4, 5])->sum();
// 15
~~~
如果集合包含嵌套數組或對象,則應該傳入一個鍵來指定要進行求和的值:
~~~
$collection = collect([
['name' => 'JavaScript: The Good Parts', 'pages' => 176],
['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);
$collection->sum('pages');
// 1272
~~~
另外,你也可以傳入回調來決定要用集合中的哪些值進行求和:
~~~
$collection = collect([
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$collection->sum(function ($product) {
return count($product['colors']);
});
// 6
~~~
#### `take()`
`take`?方法返回給定數量項目的新集合:
~~~
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]
~~~
你也可以傳入負整數從集合末尾開始獲取指定數量的項目:
~~~
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(-2);
$chunk->all();
// [4, 5]
~~~
#### `tap()`
`tap`?方法將集合傳遞給回調,在特定點「tap」集合。此舉能讓你對集合中的項目執行某些操作,而不影響集合本身:
~~~
collect([2, 4, 3, 1, 5])
->sort()
->tap(function ($collection) {
Log::debug('Values after sorting', $collection->values()->toArray());
})
->shift();
// 1
~~~
#### `times()`
靜態?`times`?方法通過回調在給定次數內創建一個新的集合:
~~~
$collection = Collection::times(10, function ($number) {
return $number * 9;
});
$collection->all();
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
~~~
使用這個方法可以與工廠結合使用創建出?[Eloquent](http://www.hmoore.net/tonyyu/laravel_5_6/786272)?模型:
~~~
$categories = Collection::times(3, function ($number) {
return factory(Category::class)->create(['name' => 'Category #'.$number]);
});
$categories->all();
/*
[
['id' => 1, 'name' => 'Category #1'],
['id' => 2, 'name' => 'Category #2'],
['id' => 3, 'name' => 'Category #3'],
]
*/
~~~
#### `toArray()`
`toArray`?方法將集合轉換成 PHP?`數組`。如果集合的值是?[Eloquent](http://www.hmoore.net/tonyyu/laravel_5_6/786272)?模型,那也會被轉換成數組:
~~~
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/
~~~
> {note}?`toArray`?也會將所有集合的嵌套對象轉換為數組。如果你想獲取原數組,就改用?[`all`](#all_155)?方法。
#### `toJson()`
`toJson`?方法將集合轉換成 JSON 字符串:
~~~
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toJson();
// '{"name":"Desk", "price":200}'
~~~
#### `transform()`
`transform`?方法迭代集合并對集合內的每個項目調用給定的回調。而集合的內容也會被回調返回的值取代:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$collection->transform(function ($item, $key) {
return $item * 2;
});
$collection->all();
// [2, 4, 6, 8, 10]
~~~
> {note} 與大多數集合的方法不同,`transform`?會修改集合本身。如果你想創建新的集合,就改用?[`map`](#map_995)?方法。
#### `union()`
`union`?方法將給定的數組添加到集合中。如果給定的數組中含有與原集合一樣的鍵,則原集合的值不會被改變:
~~~
$collection = collect([1 => ['a'], 2 => ['b']]);
$union = $collection->union([3 => ['c'], 1 => ['b']]);
$union->all();
// [1 => ['a'], 2 => ['b'], 3 => ['c']]
~~~
#### `unique()`
`unique`?方法返回集合中所有唯一的項目。返回的集合保留著原數組的鍵,所以在這個例子中,我們使用?[`values`](#values_2035)?方法來把鍵重置為連續編號的索引:
~~~
$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
~~~
處理嵌套數組或對象時,你可以指定用來決定唯一性的鍵:
~~~
$collection = collect([
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);
$unique = $collection->unique('brand');
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
]
*/
~~~
你也可以傳入自己的回調來確定項目的唯一性:
~~~
$unique = $collection->unique(function ($item) {
return $item['brand'].$item['type'];
});
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]
*/
~~~
在檢查項目值時?`unique`?方法使用的是「寬松」比較,意味著具有整數值的字符串將被視為等于相同值的整數。使用?[`uniqueStrict`](#uniqueStrict_1991)?方法可以進行「嚴格」比較 。
#### `uniqueStrict()`
這個方法的使用和?[`unique`](#unique_1933)?方法類似,只是使用了「嚴格」比較來過濾。
#### `unless()`
`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`](#when_2057)?方法。
#### `unwrap()`
靜態?`unwrap`?方法返回集合內部的可用值:
~~~
Collection::unwrap(collect('John Doe'));
// ['John Doe']
Collection::unwrap(['John Doe']);
// ['John Doe']
Collection::unwrap('John Doe');
// 'John Doe'
~~~
#### `values()`
`values`?方法返回鍵被重置為連續編號的新集合:
~~~
$collection = collect([
10 => ['product' => 'Desk', 'price' => 200],
11 => ['product' => 'Desk', 'price' => 200]
]);
$values = $collection->values();
$values->all();
/*
[
0 => ['product' => 'Desk', 'price' => 200],
1 => ['product' => 'Desk', 'price' => 200],
]
*/
~~~
#### `when()`
`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`](#unless_1995)?方法。
#### `where()`
`where`?方法通過給定的鍵值過濾集合:
~~~
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->where('price', 100);
$filtered->all();
/*
[
['product' => 'Chair', 'price' => 100],
['product' => 'Door', 'price' => 100],
]
*/
~~~
比較數值的時候,`where`?方法使用「寬松」比較,意味著具有整數值的字符串將被認為等于相同值的整數。使用?[`whereStrict`](#whereStrict_2105)?方法來進行「嚴格」比較過濾。
#### `whereStrict()`
這個方法與?[`where`](#where_2079)?方法一樣;但是會以「嚴格」比較來匹配所有值:
#### `whereIn()`
`whereIn`?方法通過給定的鍵值數組來過濾集合:
~~~
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereIn('price', [150, 200]);
$filtered->all();
/*
[
['product' => 'Bookcase', 'price' => 150],
['product' => 'Desk', 'price' => 200],
]
*/
~~~
`whereIn`?方法在檢查項目值時使用「寬松」比較,意味著具有整數值的字符串將被視為等于相同值的整數。你可以使用?[`whereInStrict`](#whereInStrict_2135)?做「嚴格」比較。
#### `whereInStrict()`
此方法的使用和?[`whereIn`](#whereIn_2109)?方法類似,只是使用了「嚴格」比較來匹配所有值。
#### `whereNotIn()`
`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`](#whereNotInStrict_2165)?做比較「嚴格」的匹配。
#### `whereNotInStrict()`
此方法的使用和?[`whereNotIn`](#whereNotIn_2139)?方法類似,只是使用了「嚴格」比較來匹配所有值。
#### `wrap()`
靜態?`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']
~~~
#### `zip()`
`zip`?方法將給定數組的值與相應索引處的原集合的值合并在一起:
~~~
$collection = collect(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]
~~~
## 高階消息傳遞
集合也提供對「高階消息傳遞」的支持,即對集合執行常見操作的快捷方式。支持高階消息傳遞的集合方法有:`average`,?`avg`,?`contains`,?`each`,?`every`,?`filter`,?`first`,?`flatMap`,?`map`,?`partition`,?`reject`,?`sortBy`,?`sortByDesc`?,`sum`?和?`unique`。
每個高階消息都能作為集合實例的動態屬性來訪問。例如,使用?`each`?高階消息傳遞在集合中的每個對象上調用一個方法:
~~~
$users = User::where('votes', '>', 500)->get();
$users->each->markAsVip();
~~~
同樣,我們可以使用?`sum`?高階消息來收集集合中「投票」總數:
~~~
$users = User::where('group', 'Development')->get();
return $users->sum->votes;
~~~
- 前言
- 翻譯說明
- 發行說明
- 升級指南
- 貢獻導引
- 入門指南
- 安裝
- 配置信息
- 文件夾結構
- Homestead
- Valet
- 部署
- 核心架構
- 請求周期
- 服務容器
- 服務提供者
- Facades
- Contracts
- 基礎功能
- 路由
- 中間件
- CSRF 保護
- 控制器
- 請求
- 響應
- 視圖
- URL
- Session
- 表單驗證
- 錯誤
- 日志
- 前端開發
- Blade 模板
- 本地化
- 前端指南
- 編輯資源 Mix
- 安全相關
- 用戶認證
- Passport OAuth 認證
- 用戶授權
- 加密解密
- 哈希
- 重置密碼
- 綜合話題
- Artisan 命令行
- 廣播系統
- 緩存系統
- 集合
- 事件系統
- 文件存儲
- 輔助函數
- 郵件發送
- 消息通知
- 擴展包開發
- 隊列
- 任務調度
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- Redis
- Eloquent ORM
- 快速入門
- 模型關聯
- Eloquent 集合
- 修改器
- API 資源
- 序列化
- 測試相關
- 快速入門
- HTTP 測試
- 瀏覽器測試 Dusk
- 數據庫測試
- 測試模擬器
- 官方擴展包
- Cashier 交易工具包
- Envoy 部署工具
- Horizon
- Scout 全文搜索
- Socialite 社會化登錄