Illuminate\Support\Collection
類爲處理數組數據提供了流式、方便的封裝。例如,查看下面的代碼,咱們使用輔助函數 collect
建立一個新的集合實例,爲每個元素運行 strtoupper
函數,而後移除全部空元素:javascript
$collection = collect(['taylor', 'abigail', null])->map(function ($name) { return strtoupper($name); })->reject(function ($name) { return empty($name); });
正如你所看到的,Collection
類容許你使用方法鏈對底層數組執行匹配和移除操做,一般,每一個 Collection
方法都會返回一個新的 Collection
實例。php
正如上面所提到的,輔助函數 collect
爲給定數組返回一個新的 Illuminate\Support\Collection
實例,因此,建立集合很簡單:css
$collection = collect([1, 2, 3]);
注:默認狀況下,Eloquent 查詢的結果老是返回
Collection
實例。html
集合是」macroable」的,這意味着咱們能夠在運行時動態添加方法到 Collection
類,例如,下面的代碼添加了 toUpper
方法到 Collection
類:java
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']
一般,咱們須要在服務提供者中聲明集合宏。laravel
本文檔接下來的部分將會介紹 Collection
類上每個有效的方法,全部這些方法均可以以方法鏈的方式流式操做底層數組。此外,幾乎每一個方法返回一個新的 Collection
實例,從而容許你在必要的時候保持原來的集合備份。算法
all()bootstrap
all
方法簡單返回集合表示的底層數組:數組
collect([1, 2, 3])->all(); // [1, 2, 3]
avg()less
avg
方法返回全部集合項的平均值:
$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo'); // 20 $average = collect([1, 1, 2, 4])->avg(); // 2
average()
avg
方法的別名。
chunk()
chunk
方法將一個集合分割成多個小尺寸的小集合:
$collection = collect([1, 2, 3, 4, 5, 6, 7]); $chunks = $collection->chunk(4); $chunks->toArray(); // [[1, 2, 3, 4], [5, 6, 7]]
當處理柵欄系統如 Bootstrap 時該方法在視圖中尤爲有用,建設你有一個想要顯示在柵欄中的 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
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
方法可用於追加給定數組或集合數據到集合末尾:
$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 ($key, $value) { return $value > 5; }); // false
contains
方法在檢查值的時候使用「寬鬆」比較,這意味着一個包含整型值的字符串和一樣的整型值是相等的(例如,'1'
和 1
相等)。要想進行嚴格比較,可使用 containsStrict
方法。
containsStrict()
這個方法和 contains
方法簽名同樣,不一樣之處在於全部值都是「嚴格」比較。
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()
dump
方法會打印集合項而不終止腳本執行:
$collection = collect(['John Doe', 'Jane Doe']); $collection->dump(); /* Collection { #items: array:2 [ 0 => "John Doe" 1 => "Jane Doe" ] } */
若是你想要在打印集合以後終止腳本執行,可使用 dd
方法來替代。
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]
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
方法。
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
。
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
方法會迭代集合並傳遞每一個值到給定回調,該回調能夠自由編輯數據項並將其返回,最後造成一個通過編輯的新集合。而後,這個數組在層級維度被扁平化:
$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']
注:不一樣於大多數其餘的集合方法,
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'], ], ] */
除了傳遞字符串key
,還能夠傳遞一個回調,回調應該返回分組後的值:
$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('email'); // false
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
類,更多細節能夠查看擴展集合部分文檔。
make()
靜態 make 方法會建立一個新的集合實例,細節可查看建立集合部分文檔。
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]
注:和大多數集合方法同樣,
map
返回新的集合實例;它並不修改所調用的實例。若是你想要改變原來的集合,使用transform
方法。
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
方法會返回給定鍵的中位數:
$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, 'name' => 'Desk']); $merged = $collection->merge(['price' => 100, 'discount' => false]); $merged->all(); // ['product_id' => 1, 'name' => 'Desk', 'price' => 100, '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
方法會返回給定鍵的衆數:
$mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo'); // [10] $mode = collect([1, 1, 2, 4])->mode(); // [1]
nth()
nth
方法組合集合中第 n-th 個元素建立一個新的集合:
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']); $collection->nth(4); // ['a', 'e']
還能夠傳遞一個 offset(偏移位置)做爲第二個參數:
$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
方法。
pad()
pad
方法將給定值填充數組直到達到指定的最大長度。該方法和 PHP 函數 array_pad 相似。
若是你想要把數據填充到左側,須要指定一個負值長度,若是指定長度絕對值小於等於數組長度那麼將不會作任何填充:
$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']
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
函數來指定返回的數據數目,若是該整型數值大於1,將會返回一個集合:
$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
方法。
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] // (隨機生成)
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
方法對它們進行從新索引。
sort()
sort
方法對集合進行排序, 排序後的集合保持原來的數組鍵,在本例中咱們使用 values
方法重置鍵爲連續編號索引:
$collection = collect([5, 3, 1, 2, 4]); $sorted = $collection->sort(); $sorted->values()->all(); // [1, 2, 3, 4, 5]
若是你須要更加高級的排序,你可使用本身的算法傳遞一個回調給 sort
方法。參考 PHP 官方文檔關於 uasort 的說明,sort
方法底層正是調用了該方法。
注:要爲嵌套集合和對象排序,查看
sortBy
和sortByDesc
方法。
sortBy()
sortBy
方法經過給定鍵對集合進行排序, 排序後的集合保持原有數組索引,在本例中,使用 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']], ] */
sortByDesc()
該方法和 sortBy
用法相同,不一樣之處在於按照相反順序進行排序。
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
方法會傳遞集合到給定回調,從而容許你在指定入口進入集合並對集合項進行處理而不影響集合自己:
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 模型時頗有用:
$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 模型,該模型也會被轉化爲數組:
$collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toArray(); /* [ ['name' => 'Desk', 'price' => 200], ] */
注:
toArray
還將全部嵌套對象轉化爲數組。若是你想要獲取底層數組,使用all
方法。
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]
注意:不一樣於大多數其它集合方法,
transform
修改集合自己,若是你想要建立一個新的集合,使用map
方法。
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
方法重置這些鍵爲連續的數字索引 :
$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()
該方法和 unique
方法簽名同樣,不一樣之處在於全部值都是「嚴格」比較。
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
。
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
。
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()
該方法和 where
用法簽名同樣,不一樣之處在於,全部值都使用「嚴格」比較。
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()
該方法和 whereIn
方法簽名相同,不一樣之處在於 whereInStrict
在比較值的時候使用「嚴格」比較。
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()
該方法和 whereNotIn
方法簽名同樣,不一樣之處在於全部值都使用「嚴格」比較。
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
、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;