鍍金池/ 教程/ PHP/ 集合
門面
Laravel Homestead
安裝及配置
測試
HTTP 中間件
加密
升級指南
幫助函數(shù)
應(yīng)用目錄結(jié)構(gòu)
集合
新手入門指南-簡單任務(wù)管理系統(tǒng)
任務(wù)調(diào)度
查詢構(gòu)建器
視圖
驗(yàn)證
Laravel Cashier(訂購&支付&發(fā)票)
本地化
隊(duì)列
調(diào)整器
分頁
文件系統(tǒng)/云存儲
貢獻(xiàn)代碼
哈希
HTTP 控制器
緩存
遷移
HTTP 請求
Laravel Elixir
發(fā)行版本說明
Envoy 任務(wù)運(yùn)行器(SSH任務(wù))
序列化
Session
起步
帶用戶功能的任務(wù)管理系統(tǒng)
起步
用戶授權(quán)
郵件
事件
填充數(shù)據(jù)
HTTP 路由
服務(wù)提供者
Blade 模板引擎
包開發(fā)
用戶認(rèn)證
Artisan 控制臺
HTTP 響應(yīng)
集合
服務(wù)容器
關(guān)聯(lián)關(guān)系
一次請求的生命周期
契約
Redis
錯誤&日志

集合

1、簡介

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

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

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

2、創(chuàng)建集合

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

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

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

3、集合方法列表

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

all()

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

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

chunk()

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

$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è)你有一個想要顯示在柵欄中的 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 方法將一個多維數(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]

contains()

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

$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

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

$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 方法將集合和另一個集合或原生 PHP數(shù)組作比較:

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

each()

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

$collection = $collection->each(function ($item, $key) {
    //
});

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

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

filter()

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

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

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

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

filter相反的方法是reject。

first()

first 方法返回通過測試集合的第一個元素:

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

你還可以調(diào)用不帶參數(shù)的 first方法來獲取集合的第一個元素,如果集合是空的,返回 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 方法通過鍵從集合中移除數(shù)據(jù)項(xiàng):

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

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

forPage()

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

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

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

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

get()

get 方法返回給定鍵的數(shù)據(jù)項(xiàng),如果不存在,返回 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)作為默認(rèn)值,如果給定鍵不存在的話回調(diào)的結(jié)果將會返回:

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

groupBy()

groupBy 方法通過給定鍵分組集合數(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,還可以傳遞一個回調(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

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

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

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

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

如果多個數(shù)據(jù)項(xiàng)有同一個鍵,只有最后一個會出現(xiàn)在新的集合中。 你可以傳遞自己的回調(diào),將會返回經(jīng)過處理的鍵的值作為新的鍵:

$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 ($key, $value) {
    return $value < 3;
});
// 2

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

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

map()

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

$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í)例。如果你想要改變原來的集合,使用transform方法。

merge()

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

$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ù)組的值將會附加到集合后面:

$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 方法通過鍵從集合中移除并返回?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)

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

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

reduce()

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

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

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

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

reject() reject 方法使用給定回調(diào)過濾集合,該回調(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 方法相對的方法是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 方法為給定值查詢集合,如果找到的話返回對應(yīng)的鍵,如果沒找到,則返回 false:

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

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

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

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

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

shift()

shift 方法從集合中移除并返回第一個數(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 方法從給定索開始返回集合的一個切片:

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

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

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

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

sort()

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

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

排序后的集合保持原來的數(shù)組鍵,在本例中我們使用values 方法重置鍵為連續(xù)編號索引。 要為嵌套集合和對象排序,查看sortBy和sortByDesc方法。 如果你需要更加高級的排序,你可以使用自己的算法傳遞一個回調(diào)給 sort 方法。參考 PHP 官方文檔關(guān)于 usort的說明,sort 方法底層正是調(diào)用了該方法。

sortBy()

sortBy 方法通過給定鍵對集合進(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)來判斷如何排序集合的值:

$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ù)來限制返回組塊的大小:

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

此外,你可以傳遞第三個參數(shù)來包含新的數(shù)據(jù)項(xiàng)來替代從集合中移除的數(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)該傳遞一個鍵用于判斷對哪些值進(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)來判斷對哪些值進(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)返回一個新的集合:

$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)化為一個原生的 PHP 數(shù)組。如果集合的值是Eloquent模型,該模型也會被轉(zhuǎn)化為數(shù)組:

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

/*
    [
        ['name' => 'Desk', 'price' => 200],
    ]
*/

注意: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 方法迭代集合并對集合中每個數(shù)據(jù)項(xiàng)調(diào)用給定回調(diào)。集合中的數(shù)據(jù)項(xiàng)將會被替代成從回調(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 修改集合本身,如果你想要創(chuàng)建一個新的集合,使用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]

返回的集合保持原來的數(shù)組鍵,在本例中我們使用values方法重置這些鍵為連續(xù)的數(shù)字索引。 處理嵌套數(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ù)據(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 方法通過給定鍵值對過濾集合:

$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)值時 where 方法使用嚴(yán)格條件約束。使用whereLoose方法過濾松散約束。

whereLoose()

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

zip()

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

$collection = collect(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]
上一篇:文件系統(tǒng)/云存儲下一篇:視圖