集合
集合
集合
簡介
Illuminate\Support\Collection
類提供了一個更具可讀性和更便于處理數(shù)組數(shù)據(jù)的封裝。具體例子請查看下面代碼。我們使用 collect
輔助函數(shù)從數(shù)組中創(chuàng)建一個新的集合實例,對其中每一個元素執(zhí)行 strtoupper
函數(shù)之后再刪除所有的空元素:
$collection = collect(['taylor', 'abigail', null])->map(function ($name) { return strtoupper($name); })->reject(function ($name) { return empty($name); });
正如你所見, Collection
類允許你鏈?zhǔn)秸{(diào)用其它方法,以達(dá)到在底層數(shù)組上流暢的執(zhí)行 map 和 reduce 操作,通常,集合是不可變的,這意味著每一個 Collection
方法都會返回一個新的 Collection
實例。
創(chuàng)建集合
如上所述, collect
輔助函數(shù)會為指定的數(shù)組返回一個新的 Illuminate\Support\Collection
實例。因此,我們可以這樣輕松的創(chuàng)建一個集合:
$collection = collect([1, 2, 3]);
{tip} 通常,Eloquent 查詢的結(jié)果返回的內(nèi)容都是
Collection
實例。
擴展集合
集合都是「可宏擴展」(macroable) 的,它允許你在執(zhí)行時將其它方法添加到 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']
通常,你應(yīng)該在 服務(wù)提供者 內(nèi)聲明集合宏。
可用方法
接下來的文檔內(nèi)容,我們會探討 Collection
類的每個方法。請牢記,所有方法都可以通過鏈?zhǔn)皆L問的形式優(yōu)雅的操作數(shù)組。而且,幾乎所有的方法都會返回一個新的 Collection
實例,允許你在必要時保存集合的原始副本:
all
average
avg
chunk
collapse
combine
concat
contains
containsStrict
count
crossJoin
dd
diff
diffAssoc
diffKeys
dump
each
eachSpread
every
except
filter
first
firstWhere
flatMap
flatten
flip
forget
forPage
get
groupBy
has
implode
intersect
intersectByKeys
isEmpty
isNotEmpty
keyBy
keys
last
macro
make
map
mapInto
mapSpread
mapToGroups
mapWithKeys
max
median
merge
min
mode
nth
only
pad
partition
pipe
pluck
pop
prepend
pull
push
put
random
reduce
reject
reverse
search
shift
shuffle
slice
some
sort
sortBy
sortByDesc
sortKeys
sortKeysDesc
splice
split
sum
take
tap
times
toArray
toJson
transform
union
unique
uniqueStrict
unless
unlessEmpty
unlessNotEmpty
unwrap
values
when
whenEmpty
whenNotEmpty
where
whereStrict
whereBetween
whereIn
whereInStrict
whereInstanceOf
whereNotBetween
whereNotIn
whereNotInStrict
wrap
zip
方法列表
all()
all
方法返回該集合表示的底層數(shù)組:
collect([1, 2, 3])->all();// [1, 2, 3]
average()
avg
方法的別名。
avg()
avg
方法返回給定鍵的 平均值 :
$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]]
這個方法在使用網(wǎng)格系統(tǒng)的 視圖 中特別適用,例如 Bootstrap。 想象你有一個 Eloquent 模型的集合要在網(wǎng)格中顯示:
@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
方法將多個數(shù)組的集合合并成一個數(shù)組的集合:
$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
方法可以將一個集合的值作為鍵,再將另一個數(shù)組或集合的值作為值合并成一個集合:
$collection = collect(['name', 'age']); $combined = $collection->combine(['George', 29]); $combined->all(); // ['name' => 'George', 'age' => 29]
concat()
concat
方法將給定的 數(shù)組
或集合值追加到集合的末尾:
$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
方法傳遞一個回調(diào)函數(shù)來執(zhí)行自己的真實測試:
$collection = collect([1, 2, 3, 4, 5]); $collection->contains(function ($value, $key) { return $value > 5; }); // false
contains
方法在檢查集合項的值時使用「寬松」比較,這意味著具有整數(shù)值的字符串將被視為等于相同值的整數(shù)。相反 containsStrict
方法則是使用「嚴(yán)格」比較進行過濾。
containsStrict()
這個方法和 contains
方法類似,但是它卻是使用了「嚴(yán)格」比較來比較所有的值。
count()
count
方法返回這個集合內(nèi)集合項的總數(shù)量:
$collection = collect([1, 2, 3, 4]); $collection->count(); // 4
crossJoin()
crossJoin
方法交叉連接指定數(shù)組或集合的值,返回所有可能排列的笛卡爾積:
$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
方法用于打印集合項并中斷腳本執(zhí)行:
$collection = collect(['John Doe', 'Jane Doe']); $collection->dd(); /* Collection { #items: array:2 [ 0 => "John Doe" 1 => "Jane Doe" ] } */
如果你不想中斷執(zhí)行腳本,請使用 dump
方法代替。
diff()
diff
方法將集合與其它集合或純 PHP 數(shù)組
進行值的比較。然后返回原集合中存在而指定集合中不存在的值:
$collection = collect([1, 2, 3, 4, 5]); $diff = $collection->diff([2, 4, 6, 8]); $diff->all(); // [1, 3, 5]
diffAssoc()
diffAssoc
方法與另外一個集合或基于它的鍵和值的 PHP 數(shù)組
進行比較。這個方法將會返回原集合不存在于指定集合的鍵 / 值對:
$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 數(shù)組
的鍵進行比較,然后返回原集合中存在而指定集合中不存在鍵所對應(yīng)的鍵 / 值對:
$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" ] } */
如果要在打印集合后終止執(zhí)行腳本,請使用 dd
方法代替。
each()
each
方法用于循環(huán)集合項并將其傳遞到回調(diào)函數(shù)中:
$collection->each(function ($item, $key) { // });
如果你想中斷對集合項的循環(huán),那么就在你的回調(diào)函數(shù)中返回 false
:
$collection->each(function ($item, $key) { if (/* 某些條件 */ ) { return false; } });
eachSpread()
eachSpread
方法用于循環(huán)集合項,將每個嵌套集合項的值傳遞給回調(diào)函數(shù):
$collection = collect([['John Doe', 35], ['Jane Doe', 33]]); $collection->eachSpread(function ($name, $age) { // });
你可以通過在回調(diào)函數(shù)里返回 false
來中斷循環(huán):
$collection->eachSpread(function ($name, $age) { return false; });
every()
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
except()
except
方法返回集合中除了指定鍵之外的所有集合項:
$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]); $filtered = $collection->except(['price', 'discount']); $filtered->all(); // ['product_id' => 1]
與 except
對應(yīng)的是 only 方法。
filter()
filter
方法使用給定的回調(diào)函數(shù)過濾集合,只保留那些通過指定條件測試的集合項:
$collection = collect([1, 2, 3, 4]); $filtered = $collection->filter(function ($value, $key) { return $value > 2; }); $filtered->all(); // [3, 4]
如果沒有提供回調(diào)函數(shù),集合中所有返回 false
的元素都會被移除:
$collection = collect([1, 2, 3, null, false, '', 0, []]); $collection->filter()->all(); // [1, 2, 3]
與 filter
對應(yīng)的是 reject 方法。
first()
first
方法返回集合中通過指定條件測試的第一個元素:
collect([1, 2, 3, 4])->first(function ($value, $key) { return $value > 2; }); // 3
你也可以不傳入?yún)?shù)調(diào)用 first
方法來獲取集合中的第一個元素。如果集合為空,則會返回 null
:
collect([1, 2, 3, 4])->first(); // 1
firstWhere()
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]
你也可以使用運算符來調(diào)用 firstWhere
方法:
$collection->firstWhere('age', '>=', 18); // ['name' => 'Diego', 'age' => 23]
和 where 方法一樣,你可以將一個參數(shù)傳遞給 firstWhere
方法。在這種情況下, firstWhere
方法將返回指定鍵的值為「真」的第一個集合項:
$collection->firstWhere('age'); // ['name' => 'Linda', 'age' => 14]
flatMap()
flatMap
方法遍歷集合并將其中的每個值傳遞到給定的回調(diào)函數(shù)。可以通過回調(diào)函數(shù)修改集合項并返回它們,從而形成一個被修改過的新集合。然后,集合轉(zhuǎn)化的數(shù)組是同級的:
$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
方法將多維集合轉(zhuǎn)為一維集合:
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]); $flattened = $collection->flatten(); $flattened->all(); // ['taylor', 'php', 'javascript'];
你可以選擇性地傳入「深度」參數(shù):
$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'], ] */
在這個例子里,調(diào)用 flatten
時不傳入深度參數(shù)的話也會將嵌套數(shù)組轉(zhuǎn)成一維的,然后返回 ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']
。傳入深度參數(shù)能讓你限制設(shè)置返回數(shù)組的層數(shù)。
flip()
flip
方法將集合的鍵和對應(yīng)的值進行互換:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $flipped = $collection->flip();$flipped->all(); // ['taylor' => 'name', 'laravel' => 'framework']
forget()
forget
方法將通過指定的鍵來移除集合中對應(yīng)的內(nèi)容:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $collection->forget('name');$collection->all(); // ['framework' => 'laravel']
{note} 與大多數(shù)集合的方法不同的是,
forget
不會返回修改后的新集合;它會直接修改原集合。
forPage()
forPage
方法返回一個含有指定頁碼數(shù)集合項的新集合。這個方法接受頁碼數(shù)作為其第一個參數(shù),每頁顯示的項數(shù)作為其第二個參數(shù):
$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
你可以任選一個默認(rèn)值作為第二個參數(shù)傳遞:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $value = $collection->get('foo', 'default-value'); // default-value
你甚至可以將一個回調(diào)函數(shù)作為默認(rèn)值傳遞。如果指定的鍵不存在,就會返回回調(diào)函數(shù)的結(jié)果:
$collection->get('email', function () { return 'default-value'; }); // default-value
groupBy()
groupBy
方法根據(jù)指定鍵對集合項進行分組:
$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'], ], ] */
你可以傳遞一個回調(diào)函數(shù)用來代替一個字符串的 鍵
。這個回調(diào)函數(shù)應(yīng)該返回你希望用來分組的鍵的值:
$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'], ], ] */
可以傳遞一個數(shù)組用于多重分組標(biāo)準(zhǔn)。每一個數(shù)組元素將對應(yīng)多維數(shù)組內(nèi)的相應(yīng)級別:
$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', 'amount' => 5]); $collection->has('product'); // true $collection->has(['product', 'amount']); // true $collection->has(['amount', 'price']); // false
implode()
implode
方法用于合并集合項。其參數(shù)取決于集合項的類型。如果集合包含數(shù)組或?qū)ο螅銘?yīng)該傳遞你希望合并的屬性的鍵,以及你希望放在值之間用來「拼接」的字符串:
$collection = collect([ ['account_id' => 1,'product' => 'Desk'], ['account_id' => 2, 'product' => 'Chair'], ]); $collection->implode('product', ', '); // Desk, Chair
如果集合中包含簡單的字符串或數(shù)值,只需要傳入「拼接」用的字符串作為該方法的唯一參數(shù)即可:
collect([1, 2, 3, 4, 5])->implode('-'); // '1-2-3-4-5'
intersect()
intersect
方法從原集合中移除在指定 數(shù)組
或集合中不存在的任何值。生成的集合將會保留原集合的鍵:
$collection = collect(['Desk', 'Sofa', 'Chair']); $intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']); $intersect->all(); // [0 => 'Desk', 2 => 'Chair']
intersectByKeys()
intersectByKeys
方法從原集合中移除在指定 數(shù)組
或集合中不存在的任何鍵:
$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'], ] */
你還可以在這個方法傳遞一個回調(diào)函數(shù)。該回調(diào)函數(shù)返回的值會作為該集合的鍵:
$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
你也可以不傳入?yún)?shù)調(diào)用 last
方法來獲取集合中的最后一個元素。如果集合為空,則返回 null
:
collect([1, 2, 3, 4])->last(); // 4
macro()
靜態(tài) macro
方法允許你在運行時將方法添加至 Collection
類。關(guān)于更多信息,請參閱 擴展集合 的文檔。
make()
靜態(tài) make
方法可以創(chuàng)建一個新的集合實例。請參閱 創(chuàng)建集合 部分。
map()
map
方法遍歷集合并將每一個值傳入給定的回調(diào)函數(shù)。該回調(diào)函數(shù)可以任意修改集合項并返回,從而生成被修改過集合項的新集合:
$collection = collect([1, 2, 3, 4, 5]); $multiplied = $collection->map(function ($item, $key) { return $item * 2; }); $multiplied->all(); // [2, 4, 6, 8, 10]
{note} 與其它大多數(shù)集合方法一樣,
map
會返回一個新的集合實例;它不會修改原集合。如果你想修改原集合,請使用transform
方法。
mapInto()
mapInto()
方法可以迭代集合,通過將值傳遞給構(gòu)造函數(shù)來創(chuàng)建給定類的新實例:
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
方法可以遍歷集合項,將每個嵌套項值給指定的回調(diào)函數(shù)。該回調(diào)函數(shù)可以自由修改該集合項并返回,從而生成被修改過集合項的新集合:
$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]
mapToGroups()
mapToGroups
方法通過給定的回調(diào)函數(shù)對集合項進行分組。該回調(diào)函數(shù)應(yīng)該返回一個包含單個鍵 / 值對的關(guān)聯(lián)數(shù)組,從而生成一個分組值的新集合:
$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']
mapWithKeys()
mapWithKeys
方法遍歷集合并將每個值傳入給定的回調(diào)函數(shù)。該回調(diào)函數(shù)將返回一個包含單個鍵 / 值對的關(guān)聯(lián)數(shù)組:
$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
方法將合并指定的數(shù)組或集合到原集合。如果給定的集合項的字符串鍵與原集合中的字符串鍵相匹配,則指定集合項的值將覆蓋原集合的值:
$collection = collect(['product_id' => 1, 'price' => 100]); $merged = $collection->merge(['price' => 200, 'discount' => false]); $merged->all(); // ['product_id' => 1, 'price' => 200, 'discount' => false]
如果指定的集合項的鍵是數(shù)字,這些值將會追加到集合的末尾:
$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
方法返回指定鍵的 眾數(shù) :
$mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo'); // [10] $mode = collect([1, 1, 2, 4])->mode(); // [1]
nth()
nth
方法創(chuàng)建由每隔 n 個元素組成的一個新集合:
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']); $collection->nth(4); // ['a', 'e']
你可以選擇傳入一個偏移位置作為第二個參數(shù):
$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
對應(yīng)的是 except 方法。
pad()
pad
方法將使用給定的值填充數(shù)組,直到數(shù)組達(dá)到指定的大小。該方法的行為與 array_pad PHP 函數(shù)功能類似。
要填充到左側(cè),你應(yīng)該使用負(fù)值。如果給定大小的絕對值小于或等于數(shù)組的長度,則不會發(fā)生填充:
$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 函數(shù)中的 list
結(jié)合使用,用來分開通過指定條件的元素以及那些不通過指定條件的元素:
$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]
pipe()
pipe
方法將集合傳給指定的回調(diào)函數(shù)并返回結(jié)果:
$collection = collect([1, 2, 3]); $piped = $collection->pipe(function ($collection) { return $collection->sum(); }); // 6
pluck()
pluck
方法可以獲取集合中指定鍵對應(yīng)的所有值:
$collection = collect([ ['product_id' => 'prod-100', 'name' => 'Desk'], ['product_id' => 'prod-200', 'name' => 'Chair'], ]); $plucked = $collection->pluck('name'); $plucked->all(); // ['Desk', 'Chair']
你也可以通過傳入第二個參數(shù)來指定生成集合的鍵:
$plucked = $collection->pluck('name', 'product_id'); $plucked->all(); // ['prod-100' => 'Desk', 'prod-200' => 'Chair']
如果存在重復(fù)的鍵,則最后一個匹配元素將被插入到彈出的集合中:
$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]
你也可以傳遞第二個參數(shù)來設(shè)置新增加集合項的鍵:
$collection = collect(['one' => 1, 'two' => 2]); $collection->prepend(0, 'zero'); $collection->all(); // ['zero' => 0, 'one' => 1, 'two' => 2]
pull()
pull
方法把指定鍵對應(yīng)的值從集合中移除并返回:
$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
方法在集合內(nèi)設(shè)置給定的鍵值對:
$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)
你可以選擇傳入一個整數(shù)到 random
來指定要獲取的隨即項的數(shù)量。只要你顯示傳遞你希望接收的數(shù)量時,則會返回項目的集合:
$random = $collection->random(3); $random->all(); // [2, 4, 5] - (retrieved randomly)
如果集合的項小于指定的數(shù)量,則該方法將拋出 InvalidArgumentException
。
reduce()
reduce
方法將每次迭代的結(jié)果傳遞給下一次迭代直到集合減少為單個值:
$collection = collect([1, 2, 3]); $total = $collection->reduce(function ($carry, $item) { return $carry + $item; }); // 6
第一次迭代時 $carry
的數(shù)值為 null
; however,你也可以通過傳入第二個參數(shù)到 reduce
來指定它的初始值:
$collection->reduce(function ($carry, $item) { return $carry + $item;}, 4); // 10
reject()
reject
方法使用指定的回調(diào)函數(shù)過濾集合。如果回調(diào)函數(shù)返回 true
就會把對應(yīng)的集合項從集合中移除:
$collection = collect([1, 2, 3, 4]); $filtered = $collection->reject(function ($value, $key) { return $value > 2; }); $filtered->all(); // [1, 2]
與 reject
方法對應(yīng)的是 filter
方法。
reverse()
reverse
方法用來倒轉(zhuǎn)集合項的順序,并保留原始的鍵:
$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
使用 「寬松」的方式進行搜索,這意味著具有整數(shù)值的字符串會被認(rèn)為等于相同值的整數(shù)。使用 「嚴(yán)格」的方式進行搜索,就傳入 true
作為該方法的第二個參數(shù):
$collection->search('4', true); // false
或者,你可以通過傳遞回調(diào)函數(shù)來搜索通過條件測試的第一個集合項:
$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]
如果你想限制返回內(nèi)容的大小,可以將你期望的大小作為第二個參數(shù)傳遞到該方法:
$slice = $collection->slice(4, 2); $slice->all(); // [5, 6]
默認(rèn)情況下,返回的內(nèi)容將會保留原始鍵。如果你不希望保留原始鍵,你可以使用 values
方法來重新建立索引。
some()
contains
方法的別名。
sort()
sort
方法對集合進行排序。排序后的集合會保留原數(shù)組的鍵,所以在這個例子我們將使用 values
方法去把鍵重置為連續(xù)編號的索引:
$collection = collect([5, 3, 1, 2, 4]); $sorted = $collection->sort(); $sorted->values()->all(); // [1, 2, 3, 4, 5]
如果你有更高級的排序需求,可以通過自己的算法將回調(diào)函數(shù)傳遞到 sort
。請參閱 PHP 文檔的 uasort
,這是集合的 sort
方法在底層所調(diào)用的。
{tip} 如果你需要對嵌套數(shù)組或?qū)ο筮M行排序,請參照
sortBy
和sortByDesc
方法。
sortBy()
sortBy
方法將根據(jù)指定鍵對集合進行排序。排序后的集合會保留原始數(shù)組的鍵,所以在這個例子中我們使用 values
方法將鍵重置為連續(xù)編號的索引:
$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], ] */
你也可以傳遞你自己的回調(diào)函數(shù)用于決定如何對集合的值進行排序:
$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
方法一樣,但是會以相反的順序來對集合進行排序。
sortKeys()
sortKeys
方法通過底層關(guān)聯(lián)數(shù)組的鍵來對集合進行排序:
$collection = collect([ 'id' => 22345, 'first' => 'John', 'last' => 'Doe', ]); $sorted = $collection->sortKeys();$sorted->all(); /* [ 'first' => 'John', 'id' => 22345, 'last' => 'Doe', ] */
sortKeysDesc()
該方法與 sortKeys
方法一樣,但是會以相反的順序來對集合進行排序。
splice()
splice
方法移除并返回指定索引開始的集合項片段:
$collection = collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2); $chunk->all(); // [3, 4, 5] $collection->all(); // [1, 2]
你可以傳遞第二個參數(shù)用以限制被刪除內(nèi)容的大?。?/p>
$collection = collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2, 1); $chunk->all(); // [3] $collection->all(); // [1, 2, 4, 5]
此外,你可以傳入含有新參數(shù)項的第三個參數(shù)來代替集合中刪除的集合項:
$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
方法返回集合內(nèi)所有項的和:
collect([1, 2, 3, 4, 5])->sum(); // 15
如果集合包含嵌套數(shù)組或?qū)ο螅瑒t應(yīng)該傳入一個鍵來指定要進行求和的值:
$collection = collect([ ['name' => 'JavaScript: The Good Parts', 'pages' => 176], ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096], ]); $collection->sum('pages'); // 1272
另外,你可以傳入自己的回調(diào)函數(shù)來決定要用集合中的哪些值進行求和:
$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
方法返回給定數(shù)量項的新集合:
$collection = collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(3); $chunk->all(); // [0, 1, 2]
你也可以傳遞負(fù)整數(shù)從集合末尾獲取指定數(shù)量的項:
$collection = collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(-2); $chunk->all(); // [4, 5]
tap()
tap
方法將給定的回調(diào)函數(shù)傳入該集合,允許你在一個特定點「tap」集合,并在不影響集合本身的情況下對集合項執(zhí)行某些操作:
collect([2, 4, 3, 1, 5]) ->sort() ->tap(function ($collection) { Log::debug('Values after sorting', $collection->values()->toArray()); }) ->shift(); // 1
times()
靜態(tài) times
方法通過調(diào)用給定次數(shù)的回調(diào)函數(shù)來創(chuàng)建新集合:
$collection = Collection::times(10, function ($number) { return $number * 9; }); $collection->all(); // [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
使用這個方法可以與工廠結(jié)合使用創(chuàng)建出 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'], ] */
toArray()
toArray
方法將集合轉(zhuǎn)換成 PHP 數(shù)組
。如果集合的值是 Eloquent 模型,那也會被轉(zhuǎn)換成數(shù)組:
$collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toArray(); /* [ ['name' => 'Desk', 'price' => 200], ] */
{note}
toArray
也會將所有集合的嵌套對象轉(zhuǎn)換為數(shù)組。如果你想獲取原數(shù)組,可以使用all
方法。
toJson()
toJson
方法將集合轉(zhuǎn)換成 JSON 字符串:
$collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toJson(); // '{"name":"Desk", "price":200}'
transform()
transform
方法迭代集合并對每一個集合項調(diào)用給定的回調(diào)函數(shù)。而集合的內(nèi)容也會被回調(diào)函數(shù)的返回值所取代:
$collection = collect([1, 2, 3, 4, 5]); $collection->transform(function ($item, $key) { return $item * 2; }); $collection->all(); // [2, 4, 6, 8, 10]
{note} 與大多數(shù)集合方法不同,
transform
會修改集合本身。如果你想創(chuàng)建新集合,可以使用map
方法。
union()
union
方法將給定的數(shù)組添加到集合。如果給定的數(shù)組含有與原集合一樣的鍵,則原集合的值不會被改變:
$collection = collect([1 => ['a'], 2 => ['b']]); $union = $collection->union([3 => ['c'], 1 => ['b']]); $union->all(); // [1 => ['a'], 2 => ['b'], 3 => ['c']]
unique()
unique
方法返回集合中所有唯一項。返回的集合保留著原數(shù)組的鍵,所以在這個例子中,我們使用 values
方法把鍵重置為連續(xù)編號的索引:
$collection = collect([1, 1, 2, 2, 3, 4, 2]); $unique = $collection->unique(); $unique->values()->all(); // [1, 2, 3, 4]
在處理嵌套數(shù)組或?qū)ο髸r,你可以指定用于確定唯一性的鍵:
$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'], ] */
你也可以通過傳遞自己的回調(diào)函數(shù)來確定項的唯一性:
$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
方法在檢查項目值時使用「寬松」模式比較,意味著具有整數(shù)值的字符串將被視為等于相同值的整數(shù)。你可以使用 uniqueStrict
方法做「嚴(yán)格」模式比較。
uniqueStrict()
這個方法與 unique
方法一樣,然而,所有的值是用 「嚴(yán)格」模式來比較的。
unless()
unless
方法當(dāng)傳入的第一個參數(shù)不為 true
的時候,將執(zhí)行給定的回調(diào)函數(shù):
$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
對應(yīng)的是 when
方法。
unlessEmpty()
whenNotEmpty
方法的別名。
unlessNotEmpty()
whenEmpty
方法的別名。
unwrap()
靜態(tài) unwrap
方法返回集合內(nèi)部的可用值:
Collection::unwrap(collect('John Doe')); // ['John Doe']Collection::unwrap(['John Doe']); // ['John Doe']Collection::unwrap('John Doe'); // 'John Doe'
values()
values
方法返回鍵被重置為連續(xù)編號的新集合:
$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
方法當(dāng)傳入的第一個參數(shù)為 true
時,將執(zhí)行給定的回調(diào)函數(shù):
$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
對應(yīng)的是 unless
方法。
whenEmpty()
whenEmpty
方法當(dāng)集合為空時,將執(zhí)行給定的回調(diào)函數(shù):
$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
對應(yīng)的是 whenNotEmpty
方法。
whenNotEmpty()
whenNotEmpty
方法當(dāng)集合不為空時,將執(zhí)行給定的回調(diào)函數(shù):
$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
對應(yīng)的是 whenEmpty
方法。
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
方法在檢查集合項值時使用「寬松」模式比較,這意味著具有整數(shù)值的字符串會被認(rèn)為等于相同值的整數(shù)。你可以使用 whereStrict
方法進行「嚴(yán)格」模式比較。
whereStrict()
這個方法與 where
方法類似;不同的是會用「嚴(yán)格」的模式比較。
whereBetween()
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], ] */
whereIn()
whereIn
會根據(jù)包含給定數(shù)組的鍵 / 值對來過濾集合:
$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
方法使用「寬松」的比較來檢查集合項的值,這意味著具有整數(shù)值的字符串會被視為等于相同值的整數(shù)。你可以使用 whereInStrict
方法進行「嚴(yán)格」模式比較。
whereInStrict()
這個方法與 whereIn
方法類似;不同的是會使用「嚴(yán)格」模式進行比較。
whereInstanceOf()
whereInstanceOf
方法根據(jù)指定的類來過濾集合:
$collection = collect([ new User, new User, new Post, ]); return $collection->whereInstanceOf(User::class);
whereNotBetween()
whereNotBetween
方法在指定的范圍內(nèi)過濾集合:
$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], ] */
whereNotIn()
whereNotIn
方法根據(jù)通過指定的鍵和不含有指定數(shù)組的值來對集合進行過濾:
$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
方法使用「寬松」模式比較來檢查集合項的值,這意味著具有整數(shù)值的字符串將被視為等于相同值的整數(shù)。你可以使用 whereNotInStrict
方法做 「嚴(yán)格」模式比較。
whereNotInStrict()
這個方法與 whereNotIn
方法類似;不同的是會使用 「嚴(yán)格」模式作比較。
wrap()
靜態(tài) wrap
方法在適當(dāng)?shù)那闆r下將指定的值放在集合中:
$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
方法將指定數(shù)組的值和相應(yīng)索引的原集合的值合并在一起:
$collection = collect(['Chair', 'Desk']); $zipped = $collection->zip([100, 200]); $zipped->all(); // [['Chair', 100], ['Desk', 200]]
高階消息傳遞
集合也提供對「高階消息傳遞」的支持,即集合常見操作的快捷方式。支持高階消息傳遞的集合方法有: average
, avg
, contains
, each
, every
, filter
, first
, flatMap
, groupBy
, keyBy
, map
, max
, min
, partition
, reject
, some
, sortBy
, sortByDesc
, sum
, and unique
。
每個高階消息傳遞都能作為集合實例的動態(tài)的屬性來訪問。例如,使用 each
高階消息傳遞在集合中的每個對象上調(diào)用一個方法:
$users = User::where('votes', '>', 500)->get(); $users->each->markAsVip();
同樣,我們可以使用 sum
高階消息傳遞來收集 users 集合中的「投票」總數(shù):
$users = User::where('group', 'Development')->get(); return $users->sum->votes;