Laravel5 集合Collection

今天看代碼學(xué)到了一個(gè)操作數(shù)組的新用法,搜了一下文檔,發(fā)現(xiàn)很多奇妙的用處,記錄一下,原文文章《[ Laravel 5.7 文檔 ] 進(jìn)階系列 —— 集合》

1、簡(jiǎn)介

Illuminate\Support\[Collection](http://laravelacademy.org/tags/collection "View all posts in Collection")類為處理數(shù)組數(shù)據(jù)提供了平滑、方便的封裝。例如,查看下面的代碼,我們使用幫助函數(shù)collect創(chuàng)建一個(gè)新的集合實(shí)例,為每一個(gè)元素運(yùn)行strtoupper函數(shù),然后移除所有空元素:

$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
                  return strtoupper($name);
              })->reject(function ($name) {
                  return empty($name);
              });

正如你所看到的,Collection類允許你使用方法鏈對(duì)底層數(shù)組執(zhí)行匹配和減少操作,通常,沒(méi)個(gè)Collection方法都會(huì)返回一個(gè)新的Collection實(shí)例。

2、創(chuàng)建集合

正如上面所提到的,幫助函數(shù)collect為給定數(shù)組返回一個(gè)新的Illuminate\Support\Collection實(shí)例,所以,創(chuàng)建集合很簡(jiǎn)單:

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

默認(rèn)情況下,Eloquent模型的集合總是返回Collection實(shí)例,此外,不管是在何處,只要方法都可以自由使用Collection類。

3、集合方法列表

文檔接下來(lái)的部分我們將會(huì)討論Collection類上每一個(gè)有效的方法,所有這些方法都可以以方法鏈的方式平滑的操作底層數(shù)組。此外,幾乎每個(gè)方法返回一個(gè)新的Collection實(shí)例,允許你在必要的時(shí)候保持原來(lái)的集合備份。

all()

all方法簡(jiǎn)單返回集合表示的底層數(shù)組:

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

chunk()

chunk方法將一個(gè)集合分割成多個(gè)小尺寸的小集合:

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

當(dāng)處理柵欄系統(tǒng)如Bootstrap時(shí)該方法在視圖中尤其有用,建設(shè)你有一個(gè)想要顯示在柵欄中的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</pre>

collapse()

collapse方法將一個(gè)多維數(shù)組集合收縮成一個(gè)一維數(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]

contains()

contains方法判斷集合是否包含一個(gè)給定項(xiàng):

$collection = collect(['name' => 'Desk', 'price' => 100]);

$collection->contains('Desk');
// true
$collection->contains('New York');
// false

你還可以傳遞一個(gè)鍵值對(duì)到contains方法,這將會(huì)判斷給定鍵值對(duì)是否存在于集合中:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);

$collection->contains('product', '[Bookcase](https://www.baidu.com/s?wd=Bookcase&tn=24004469_oem_dg&rsv_dl=gh_pl_sl_csd)');
// false

最后,你還可以傳遞一個(gè)回調(diào)到contains方法來(lái)執(zhí)行自己的真實(shí)測(cè)試:

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

count()

count方法返回集合中所有項(xiàng)的數(shù)目:

$collection = collect([1, 2, 3, 4]);
$collection->count();
// 4

diff()

diff方法將集合和另一個(gè)集合或原生PHP數(shù)組作比較:

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

#### each()

`each`方法迭代集合中的數(shù)據(jù)項(xiàng)并傳遞每個(gè)數(shù)據(jù)項(xiàng)到給定回調(diào):

<pre style="box-sizing: border-box; outline: 0px; margin: 10px 0px; padding: 9.5px; position: relative; font-family: Monaco, Menlo, Consolas, &quot;Courier New&quot;, monospace; white-space: pre-wrap; overflow-wrap: break-word; overflow: auto; font-size: 13px; line-height: 1.42857; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial; border: 1px solid rgb(204, 204, 204); vertical-align: baseline; max-width: 100%; word-break: break-all; background: rgb(245, 245, 245);">$collection = $collection->each(function ($item, $key) {
    //
});

回調(diào)返回false將會(huì)終止循環(huán):

$collection = $collection->each(function ($item, $key) {
    if (/* some condition */) {
        return false;
    }
});

filter()

filter方法通過(guò)給定回調(diào)過(guò)濾集合,只有通過(guò)給定測(cè)試的數(shù)據(jù)項(xiàng)才會(huì)保留下來(lái):

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

$filtered = $collection->filter(function ($item) {
    return $item > 2;
});

$filtered->all();
// [3, 4]

filter相反的方法是reject。

first()

first方法返回通過(guò)測(cè)試集合的第一個(gè)元素:

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

你還可以調(diào)用不帶參數(shù)的first方法來(lái)獲取集合的第一個(gè)元素,如果集合是空的,返回null:

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

flatten()

flatten方法將多維度的集合變成一維的:

$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['taylor', 'php', 'javascript'];

flip()

flip方法將集合的鍵值做交換:

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$flipped = $collection->flip();
$flipped->all();
// ['taylor' => 'name', 'laravel' => 'framework']

forget()

forget方法通過(guò)鍵從集合中移除數(shù)據(jù)項(xiàng):

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$collection->forget('name');
$collection->all();
// [framework' => 'laravel']

注意:不同于大多數(shù)的集合方法,forget不返回新的修改過(guò)的集合;它只修改所調(diào)用的集合。

forPage()

forPage方法返回新的包含給定頁(yè)數(shù)數(shù)據(jù)項(xiàng)的集合:

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

$collection->all();
// [4, 5, 6]

該方法需要傳入頁(yè)數(shù)和每頁(yè)顯示數(shù)目參數(shù)。

get()

get方法返回給定鍵的數(shù)據(jù)項(xiàng),如果不存在,返回null:

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('name');
// taylor

你可以選擇傳遞默認(rèn)值作為第二個(gè)參數(shù):

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('foo', 'default-value');
// default-value

你甚至可以傳遞回調(diào)作為默認(rèn)值,如果給定鍵不存在的話回調(diào)的結(jié)果將會(huì)返回:

$collection->get('email', function () {
return 'default-value';});
// default-value

groupBy()

groupBy方法通過(guò)給定鍵分組集合數(shù)據(jù)項(xiàng):

$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,還可以傳遞一個(gè)回調(diào),回調(diào)應(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'],
    ],
]
*/

has()

has方法判斷給定鍵是否在集合中存在:

$collection = collect(['account_id' => 1, 'product' => 'Desk']);$collection->has('email');// false

implode()

implode方法連接集合中的數(shù)據(jù)項(xiàng)。其參數(shù)取決于集合中數(shù)據(jù)項(xiàng)的類型。

如果集合包含數(shù)組或?qū)ο?,?yīng)該傳遞你想要連接的屬性鍵,以及你想要放在值之間的 “粘合”字符串:

$collection = collect([    ['account_id' => 1, 'product' => 'Desk'],    ['account_id' => 2, 'product' => 'Chair'],]); $collection->implode('product', ', ');// Desk, Chair

如果集合包含簡(jiǎn)單的字符串或數(shù)值,只需要傳遞“粘合”字符串作為唯一參數(shù)到該方法:

collect([1, 2, 3, 4, 5])->implode('-');// '1-2-3-4-5'

intersect()

intersect方法返回兩個(gè)集合的交集:

$collection = collect(['Desk', 'Sofa', 'Chair']);$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);$intersect->all();// [0 => 'Desk', 2 => 'Chair']

正如你所看到的,結(jié)果集合只保持原來(lái)集合的鍵。

isEmpty()

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

collect([])->isEmpty();// true

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'],    ]*/

如果多個(gè)數(shù)據(jù)項(xiàng)有同一個(gè)鍵,只有最后一個(gè)會(huì)出現(xiàn)在新的集合中。

你可以傳遞自己的回調(diào),將會(huì)返回經(jīng)過(guò)處理的鍵的值作為新的鍵:

$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方法返回通過(guò)測(cè)試的集合的最后一個(gè)元素:

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

還可以調(diào)用無(wú)參的last方法來(lái)獲取集合的最后一個(gè)元素。如果集合為空。返回null:

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

map()

map方法遍歷集合并傳遞每個(gè)值給給定回調(diào)。該回調(diào)可以修改數(shù)據(jù)項(xiàng)并返回,從而生成一個(gè)新的經(jīng)過(guò)修改的集合:

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

注意:和大多數(shù)集合方法一樣,map返回新的集合實(shí)例;它并不修改所調(diào)用的實(shí)例。如果你想要改變?cè)瓉?lái)的集合,使用transform方法。

merge()

merge方法合并給定數(shù)組到集合。該數(shù)組中的任何字符串鍵匹配集合中的字符串鍵的將會(huì)重寫集合中的值:

$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]

如果給定數(shù)組的鍵是數(shù)字,數(shù)組的值將會(huì)附加到集合后面:

$collection = collect(['Desk', 'Chair']);$merged = $collection->merge(['Bookcase', 'Door']);$merged->all();// ['Desk', 'Chair', 'Bookcase', 'Door']

pluck()

pluck方法為給定鍵獲取所有集合值:

$collection = collect([    ['product_id' => 'prod-100', 'name' => 'Desk'],    ['product_id' => 'prod-200', 'name' => 'Chair'],]); $plucked = $collection->pluck('name'); $plucked->all();// ['Desk', 'Chair']

還可以指定你想要結(jié)果集合如何設(shè)置鍵:

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

pop()

pop方法移除并返回集合中最后面的數(shù)據(jù)項(xiàng):

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

prepend()

prepend方法添加數(shù)據(jù)項(xiàng)到集合開頭:

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

pull()

pull方法通過(guò)鍵從集合中移除并返回?cái)?shù)據(jù)項(xiàng):

$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);$collection->pull('name');// 'Desk'$collection->all();// ['product_id' => 'prod-100']

push()

push方法附加數(shù)據(jù)項(xiàng)到集合結(jié)尾:

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

put()

put方法在集合中設(shè)置給定鍵和值:

$collection = collect(['product_id' => 1, 'name' => 'Desk']);$collection->put('price', 100);$collection->all();// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

random()

random 方法從集合中返回隨機(jī)數(shù)據(jù)項(xiàng):

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

你可以傳遞一個(gè)整型數(shù)據(jù)到random函數(shù),如果該整型數(shù)值大于1,將會(huì)返回一個(gè)集合:

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

reduce()

reduce 方法用于減少集合到單個(gè)值,傳遞每個(gè)迭代結(jié)果到隨后的迭代:

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

在第一次迭代時(shí)$carry的值是null;然而,你可以通過(guò)傳遞第二個(gè)參數(shù)到reduce來(lái)指定其初始值:

$collection->reduce(function ($carry, $item) {    return $carry + $item;}, 4);// 10

reject()

reject方法使用給定回調(diào)過(guò)濾集合,該回調(diào)應(yīng)該為所有它想要從結(jié)果集合中移除的數(shù)據(jù)項(xiàng)返回true:

$collection = collect([1, 2, 3, 4]); $filtered = $collection->reject(function ($item) {    return $item > 2;}); $filtered->all();// [1, 2]

reduce方法相對(duì)的方法是filter方法。

reverse()

reverse方法將集合數(shù)據(jù)項(xiàng)的順序顛倒:

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

search()

search方法為給定值查詢集合,如果找到的話返回對(duì)應(yīng)的鍵,如果沒(méi)找到,則返回false

$collection = collect([2, 4, 6, 8]);$collection->search(4);// 1

上面的搜索使用的是松散比較,要使用嚴(yán)格比較,傳遞true作為第二個(gè)參數(shù)到該方法:

$collection->search('4', true);// false

此外,你還可以傳遞自己的回調(diào)來(lái)搜索通過(guò)測(cè)試的第一個(gè)數(shù)據(jù)項(xiàng):

$collection->search(function ($item, $key) {    return $item > 5;});// 2

shift()

shift方法從集合中移除并返回第一個(gè)數(shù)據(jù)項(xiàng):

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

shuffle()

shuffle方法隨機(jī)打亂集合中的數(shù)據(jù)項(xiàng):

$collection = collect([1, 2, 3, 4, 5]);$shuffled = $collection->shuffle();$shuffled->all();// [3, 2, 5, 1, 4] // (generated randomly)

slice()

slice方法從給定索開始返回集合的一個(gè)切片:

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

如果你想要限制返回切片的尺寸,將尺寸值作為第二個(gè)參數(shù)傳遞到該方法:

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

返回的切片有新的、數(shù)字化索引的鍵,如果你想要保持原有的鍵,可以傳遞第三個(gè)參數(shù)true到該方法。

sort()

sort方法對(duì)集合進(jìn)行排序:

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

排序后的集合保持原來(lái)的數(shù)組鍵,在本例中我們使用values 方法重置鍵為連續(xù)編號(hào)索引。

要為嵌套集合和對(duì)象排序,查看sortBysortByDesc方法。

如果你需要更加高級(jí)的排序,你可以使用自己的算法傳遞一個(gè)回調(diào)給sort方法。參考PHP官方文檔關(guān)于 [usort](http://php.net/manual/en/function.usort.php#refsect1-function.usort-parameters)的說(shuō)明,sort方法底層正是調(diào)用了該方法。

sortBy()

sortBy方法通過(guò)給定鍵對(duì)集合進(jìn)行排序:

$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],    ]*/

排序后的集合保持原有數(shù)組索引,在本例中,使用values`方法重置鍵為連續(xù)索引。

你還可以傳遞自己的回調(diào)來(lái)判斷如何排序集合的值:

$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用法相同,不同之處在于按照相反順序進(jìn)行排序。

splice()

splice方法在從給定位置開始移除并返回?cái)?shù)據(jù)項(xiàng)切片:

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

你可以傳遞參數(shù)來(lái)限制返回組塊的大?。?/p>

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

此外,你可以傳遞第三個(gè)參數(shù)來(lái)包含新的數(shù)據(jù)項(xiàng)來(lái)替代從集合中移除的數(shù)據(jù)項(xiàng):

$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]

sum()

sum方法返回集合中所有數(shù)據(jù)項(xiàng)的和:

collect([1, 2, 3, 4, 5])->sum();// 15

如果集合包含嵌套數(shù)組或?qū)ο?,?yīng)該傳遞一個(gè)鍵用于判斷對(duì)哪些值進(jìn)行求和運(yùn)算:

$collection = collect([    ['name' => 'JavaScript: The Good Parts', 'pages' => 176],    ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],]); $collection->sum('pages');// 1272

此外,你還可以傳遞自己的回調(diào)來(lái)判斷對(duì)哪些值進(jìn)行求和:

$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ù)目的數(shù)據(jù)項(xiàng)返回一個(gè)新的集合:

$collection = collect([0, 1, 2, 3, 4, 5]);$chunk = $collection->take(3);$chunk->all();// [0, 1, 2]

你還可以傳遞負(fù)數(shù)從集合末尾開始獲取指定數(shù)目的數(shù)據(jù)項(xiàng):

$collection = collect([0, 1, 2, 3, 4, 5]);$chunk = $collection->take(-2);$chunk->all();// [4, 5]

toArray()

toArray方法將集合轉(zhuǎn)化為一個(gè)原生的PHP數(shù)組。如果集合的值是Eloquent模型,該模型也會(huì)被轉(zhuǎn)化為數(shù)組:

$collection = collect(['name' => 'Desk', 'price' => 200]);$collection->toArray(); /*    [        ['name' => 'Desk', 'price' => 200],    ]*/

注意:toArray還將所有嵌套對(duì)象轉(zhuǎn)化為數(shù)組。如果你想要獲取底層數(shù)組,使用all方法。

toJson()

toJson方法將集合轉(zhuǎn)化為JSON:

$collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toJson();// '{"name":"Desk","price":200}'

transform()

transform方法迭代集合并對(duì)集合中每個(gè)數(shù)據(jù)項(xiàng)調(diào)用給定回調(diào)。集合中的數(shù)據(jù)項(xiàng)將會(huì)被替代成從回調(diào)中返回的值:

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

注意:不同于大多數(shù)其它集合方法,transform修改集合本身,如果你想要?jiǎng)?chuàng)建一個(gè)新的集合,使用map方法。

unique()

unique方法返回集合中所有的唯一數(shù)據(jù)項(xiàng):

$collection = collect([1, 1, 2, 2, 3, 4, 2]);$unique = $collection->unique();$unique->values()->all();// [1, 2, 3, 4]

返回的集合保持原來(lái)的數(shù)組鍵,在本例中我們使用values方法重置這些鍵為連續(xù)的數(shù)字索引。

處理嵌套數(shù)組或?qū)ο髸r(shí),可以指定用于判斷唯一的鍵:

$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ù)據(jù)項(xiàng)唯一性:

$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'],    ]*/

values()

values方法使用重置為連續(xù)整型數(shù)字的鍵返回新的集合:

$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],    ]*/

where()

where方法通過(guò)給定鍵值對(duì)過(guò)濾集合:

$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],]*/

檢查數(shù)據(jù)項(xiàng)值時(shí)where方法使用嚴(yán)格條件約束。使用whereLoose方法過(guò)濾松散約束。

whereLoose()

該方法和where使用方法相同,不同之處在于whereLoose在比較值的時(shí)候使用松散約束。

zip()

zip方法在于集合的值相應(yīng)的索引處合并給定數(shù)組的值:

$collection = collect(['Chair', 'Desk']);$zipped = $collection->zip([100, 200]);$zipped->all();// [['Chair', 100], ['Desk', 200]]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容