集合

简介

Illuminate\Support\Collection 类提供一个流畅、便利的封装来操控数组数据。如下面的示例代码,我们用 collect 函数从数组中创建新的集合实例,对每一个元素运行 strtoupper 函数,然后移除所有的空元素:

  1. $collection = collect(['taylor', 'abigail', null])->map(function ($name) {
  2. return strtoupper($name);
  3. })
  4. ->reject(function ($name) {
  5. return empty($name);
  6. });

如你所见,Collection 类支持链式调用,一般来说,每一个 Collection 方法会返回一个全新的 Collection 实例,你可以放心地进行链接调用。

创建集合

如上所述,collect 辅助函数会利用传入的数组生成一个新的 Illuminate\Support\Collection 实例。所以要创建一个集合就这么简单:

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

默认 Eloquent 模型的集合总是以 Collection 实例返回;然而,你可以随意的在你应用程序中使用 Collection 类。

可用的方法

在这份文档剩余的部份,我们将会探讨 Collection 类的所有方法。要记得的是,所有方法都支持链式调用,几乎所有的方法都会返回新的 Collection 实例,让你保留原版的集合以备不时之需。

你可以从这张数据库表中选择任一方法看使用例子:

方法清单

all() {#collection-method .first-collection-method}

返回该集合所代表的底层 数组

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

avg() {#collection-method}

返回集合中所有项目的平均值:

  1. collect([1, 2, 3, 4, 5])->avg();
  2. // 3

如果集合包含了嵌套数组或对象,你可以通过传递「键」来指定使用哪些值计算平均值:

  1. $collection = collect([
  2. ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
  3. ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
  4. ]);
  5. $collection->avg('pages');
  6. // 636

chunk() {#collection-method}

将集合拆成多个指定大小的较小集合:

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

这个方法在适用于网格系统如 Bootstrap视图 。想像你有一个 Eloquent 模型的集合要显示在一个网格内:

  1. @foreach ($products->chunk(3) as $chunk)
  2. <div class="row">
  3. @foreach ($chunk as $product)
  4. <div class="col-xs-4">{{ $product->name }}</div>
  5. @endforeach
  6. </div>
  7. @endforeach

collapse() {#collection-method}

将多个数组组成的集合合成单个数组集合:

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

contains() {#collection-method}

判断集合是否含有指定项目:

  1. $collection = collect(['name' => 'Desk', 'price' => 100]);
  2. $collection->contains('Desk');
  3. // true
  4. $collection->contains('New York');
  5. // false

你可以将一对键/值传入 contains 方法,用来判断该组合是否存在于集合内:

  1. $collection = collect([
  2. ['product' => 'Desk', 'price' => 200],
  3. ['product' => 'Chair', 'price' => 100],
  4. ]);
  5. $collection->contains('product', 'Bookcase');
  6. // false

最后,你也可以传入一个回调函数到 contains 方法内运行你自己的判断语句:

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

count() {#collection-method}

返回该集合内的项目总数:

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

diff() {#collection-method}

将集合与其它集合或纯 PHP 数组进行比较:

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

each() {#collection-method}

遍历集合中的项目,并将之传入回调函数:

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

回调函数返回 false 以中断循环:

  1. $collection = $collection->each(function ($item, $key) {
  2. if (/* some condition */) {
  3. return false;
  4. }
  5. });

every() {#collection-method}

创建一个包含每 第 n 个 元素的新集合:

  1. $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
  2. $collection->every(4);
  3. // ['a', 'e']

你可以选择性的传递偏移值作为第二个参数:

  1. $collection->every(4, 1);
  2. // ['b', 'f']

except() {#collection-method}

返回集合中除了指定键的所有项目:

  1. $collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
  2. $filtered = $collection->except(['price', 'discount']);
  3. $filtered->all();
  4. // ['product_id' => 1, 'name' => 'Desk']

except 相反的方法请查看 only

filter() {#collection-method}

使用回调函数筛选集合,只留下那些通过判断测试的项目:

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

filter 相反的方法可以查看 reject

first() {#collection-method}

返回集合第一个通过指定测试的元素:

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

你也可以不传入参数使用 first 方法以获取集合中第一个元素。如果集合是空的,则会返回 null

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

flatten() {#collection-method}

将多维集合转为一维集合:

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

flip() {#collection-method}

将集合中的键和对应的数值进行互换:

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

forget() {#collection-method}

通过集合的键来移除掉集合中的一个项目:

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

注意:与大多数其它集合的方法不同,forget 不会返回修改过后的新集合;它会直接修改调用它的集合。

forPage() {#collection-method}

返回可用来在指定页码显示项目的新集合:

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

这个方法需要「页码」和「每页显示数量」。

get() {#collection-method}

返回指定键的项目。如果该键不存在,则返回 null

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

你可以选择性地传入一个默认值作为第二个参数:

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

你甚至可以传入回调函数当默认值。如果指定的键不存在,就会返回回调函数的运行结果:

  1. $collection->get('email', function () {
  2. return 'default-value';
  3. });
  4. // default-value

groupBy() {#collection-method}

根据指定的「键」为集合内的项目分组:

  1. $collection = collect([
  2. ['account_id' => 'account-x10', 'product' => 'Chair'],
  3. ['account_id' => 'account-x10', 'product' => 'Bookcase'],
  4. ['account_id' => 'account-x11', 'product' => 'Desk'],
  5. ]);
  6. $grouped = $collection->groupBy('account_id');
  7. $grouped->toArray();
  8. /*
  9. [
  10. 'account-x10' => [
  11. ['account_id' => 'account-x10', 'product' => 'Chair'],
  12. ['account_id' => 'account-x10', 'product' => 'Bookcase'],
  13. ],
  14. 'account-x11' => [
  15. ['account_id' => 'account-x11', 'product' => 'Desk'],
  16. ],
  17. ]
  18. */

除了传入字符串的「键」之外,你也可以传入回调函数。该函数应该返回你希望用来分组的键的值。

  1. $grouped = $collection->groupBy(function ($item, $key) {
  2. return substr($item['account_id'], -3);
  3. });
  4. $grouped->toArray();
  5. /*
  6. [
  7. 'x10' => [
  8. ['account_id' => 'account-x10', 'product' => 'Chair'],
  9. ['account_id' => 'account-x10', 'product' => 'Bookcase'],
  10. ],
  11. 'x11' => [
  12. ['account_id' => 'account-x11', 'product' => 'Desk'],
  13. ],
  14. ]
  15. */

has() {#collection-method}

检查集合中是否含有指定的「键」:

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

implode() {#collection-method}

implode 方法合并集合中的项目。它的参数依集合中的项目类型而定。

假如集合含有数组或对象,你应该传入你希望连接的属性的「键」,以及你希望放在数值之间的拼接字符串:

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

假如集合只含有简单的字符串或数字,则只需要传入拼接的字符串作为该方法的唯一参数即可:

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

intersect() {#collection-method}

移除任何指定 数组 或集合内所没有的数值:

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

相当于取「交集」。

isEmpty() {#collection-method}

如果集合是空的,isEmpty 方法会返回 true:否则返回 false

  1. collect([])->isEmpty();
  2. // true

keyBy() {#collection-method}

以指定键的值作为集合项目的键:

  1. $collection = collect([
  2. ['product_id' => 'prod-100', 'name' => 'desk'],
  3. ['product_id' => 'prod-200', 'name' => 'chair'],
  4. ]);
  5. $keyed = $collection->keyBy('product_id');
  6. $keyed->all();
  7. /*
  8. [
  9. 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
  10. 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
  11. ]
  12. */

如果多个项目有同样的键,只有最后一个会出现在新的集合内。

你也可以传入自己的回调函数,该函数应该返回集合的键的值:

  1. $keyed = $collection->keyBy(function ($item) {
  2. return strtoupper($item['product_id']);
  3. });
  4. $keyed->all();
  5. /*
  6. [
  7. 'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
  8. 'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
  9. ]
  10. */

keys() {#collection-method}

返回该集合所有的键:

  1. $collection = collect([
  2. 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
  3. 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
  4. ]);
  5. $keys = $collection->keys();
  6. $keys->all();
  7. // ['prod-100', 'prod-200']

last() {#collection-method}

返回集合中,最后一个通过指定测试的元素:

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

你也可以不传入参数使用 last 方法以获取集合中最后一个元素。如果集合是空的,则会返回 null

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

map() {#collection-method}

遍历整个集合并将每一个数值传入回调函数。回调函数可以任意修改并返回项目,形成修改过的项目组成的新集合:

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

注意:正如集合大多数其它的方法一样,map 返回一个新集合实例;它并没有修改被调用的集合。假如你想改变原始的集合,得使用 transform 方法。

max() {#collection-method}

计算指定键的最大值:

  1. $max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
  2. // 20
  3. $max = collect([1, 2, 3, 4, 5])->max();
  4. // 5

merge() {#collection-method}

合并数组进集合。数组「键」对应的数值会覆盖集合「键」对应的数值:

  1. $collection = collect(['product_id' => 1, 'name' => 'Desk']);
  2. $merged = $collection->merge(['price' => 100, 'discount' => false]);
  3. $merged->all();
  4. // ['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]

如果指定数组的「键」为数字,则「值」将会合并到集合的后面:

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

min() {#collection-method}

计算指定「键」的最小值:

  1. $min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
  2. // 10
  3. $min = collect([1, 2, 3, 4, 5])->min();
  4. // 1

only() {#collection-method}

返回集合中指定键的所有项目:

  1. $collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
  2. $filtered = $collection->only(['product_id', 'name']);
  3. $filtered->all();
  4. // ['product_id' => 1, 'name' => 'Desk']

only 相反的方法请查看 except

pluck() {#collection-method}

获取所有集合中指定「键」对应的值:

  1. $collection = collect([
  2. ['product_id' => 'prod-100', 'name' => 'Desk'],
  3. ['product_id' => 'prod-200', 'name' => 'Chair'],
  4. ]);
  5. $plucked = $collection->pluck('name');
  6. $plucked->all();
  7. // ['Desk', 'Chair']

你也可以指定要怎么给最后出来的集合分配键:

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

pop() {#collection-method}

移除并返回集合最后一个项目:

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

prepend() {#collection-method}

在集合前面增加一个项目:

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

你可以传递选择性的第二个参数来设置前置项目的键:

  1. $collection = collect(['one' => 1, 'two', => 2]);
  2. $collection->prepend(0, 'zero');
  3. $collection->all();
  4. // ['zero' => 0, 'one' => 1, 'two', => 2]

pull() {#collection-method}

把「键」对应的值从集合中移除并返回:

  1. $collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);
  2. $collection->pull('name');
  3. // 'Desk'
  4. $collection->all();
  5. // ['product_id' => 'prod-100']

push() {#collection-method}

在集合的后面新添加一个元素:

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

put() {#collection-method}

在集合内设置一个「键/值」:

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

random() {#collection-method}

random 方法从集合中随机返回一个项目:

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $collection->random();
  3. // 4 - (随机返回)

你可以选择性地传入一个整数到 random。如果该整数大于 1,则会返回一个集合:

  1. $random = $collection->random(3);
  2. $random->all();
  3. // [2, 4, 5] - (随机返回)

reduce() {#collection-method}

reduce 方法将集合缩减到单个数值,该方法会将每次迭代的结果传入到下一次迭代:

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

第一次迭代时 $carry 的数值为 null;然而你也可以传入第二个参数进 reduce 以指定它的初始值:

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

reject() {#collection-method}

reject 方法以指定的回调函数筛选集合。该回调函数应该对希望从最终集合移除掉的项目返回 true

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

reject 相反的方法可以查看 filter 方法。

reverse() {#collection-method}

reverse 方法倒转集合内项目的顺序:

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

search() {#collection-method}

search 方法在集合内搜索指定的数值并返回找到的键。假如找不到项目,则返回 false

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

搜索是用「宽松」比对来进行。要使用严格比对,就传入 true 为该方法的第二个参数:

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

另外,你可以传入你自己的回调函数来搜索第一个通过你判断测试的项目:

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

shift() {#collection-method}

shift 方法移除并返回集合的第一个项目:

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

shuffle() {#collection-method}

shuffle 方法随机排序集合的项目:

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

slice() {#collection-method}

slice 方法返回集合从指定索引开始的一部分切片:

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

如果你想限制返回切片的大小,就传入想要的大小为方法的第二个参数:

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

返回的切片将会有以数字索引的新键。假如你希望保留原始的键,传入 true 为方法的第三个参数。

sort() {#collection-method}

对集合排序:

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

排序过的集合保有原来的数组键。在这个例子中我们用了 values 方法重设键为连续的数字索引。

要排序内含数组或对象的集合,见 sortBysortByDesc 方法。

假如你需要更高级的排序,你可以传入回调函数以你自己的算法进行排序。参考 PHP 文档的 usort,这是集合的 sort 方法在背后所调用的函数。

sortBy() {#collection-method}

以指定的键排序集合:

  1. $collection = collect([
  2. ['name' => 'Desk', 'price' => 200],
  3. ['name' => 'Chair', 'price' => 100],
  4. ['name' => 'Bookcase', 'price' => 150],
  5. ]);
  6. $sorted = $collection->sortBy('price');
  7. $sorted->values()->all();
  8. /*
  9. [
  10. ['name' => 'Chair', 'price' => 100],
  11. ['name' => 'Bookcase', 'price' => 150],
  12. ['name' => 'Desk', 'price' => 200],
  13. ]
  14. */

排序过的集合保有原来的数组键。在这个例子中我们用了 values 方法重设键为连续的数字索引。

你也可以传入自己的回调函数以决定如何排序集合数值:

  1. $collection = collect([
  2. ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
  3. ['name' => 'Chair', 'colors' => ['Black']],
  4. ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
  5. ]);
  6. $sorted = $collection->sortBy(function ($product, $key) {
  7. return count($product['colors']);
  8. });
  9. $sorted->values()->all();
  10. /*
  11. [
  12. ['name' => 'Chair', 'colors' => ['Black']],
  13. ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
  14. ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
  15. ]
  16. */

sortByDesc() {#collection-method}

sortBy 有着一样的形式,但是会以相反的顺序来排序集合:

splice() {#collection-method}

返回从指定的索引开始的一小切片项目,原本集合也会被切除:

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

你可以传入第二个参数以限制大小:

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

此外,你可以传入含有新项目的第三个参数以取代集合中被移除的项目:

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

sum() {#collection-method}

返回集合内所有项目的总和:

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

如果集合包含数组或对象,你应该传入一个「键」来指定要用哪些数值来计算总合:

  1. $collection = collect([
  2. ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
  3. ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
  4. ]);
  5. $collection->sum('pages');
  6. // 1272

此外,你可以传入自己的回调函数来决定要用哪些数值来计算总合:

  1. $collection = collect([
  2. ['name' => 'Chair', 'colors' => ['Black']],
  3. ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
  4. ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
  5. ]);
  6. $collection->sum(function ($product) {
  7. return count($product['colors']);
  8. });
  9. // 6

take() {#collection-method}

返回有着指定数量项目的集合:

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

你也可以传入负整数以获取从集合后面来算指定数量的项目:

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

toArray() {#collection-method}

将集合转换成纯 PHP 数组。假如集合的数值是 Eloquent 模型,也会被转换成数组:

  1. $collection = collect(['name' => 'Desk', 'price' => 200]);
  2. $collection->toArray();
  3. /*
  4. [
  5. ['name' => 'Desk', 'price' => 200],
  6. ]
  7. */

注意:toArray 也会转换所有内嵌的对象为数组。假如你希望获取原本的底层数组,改用 all 方法。

toJson() {#collection-method}

将集合转换成 JSON:

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

transform() {#collection-method}

遍历集合并对集合内每一个项目调用指定的回调函数。集合的项目将会被回调函数返回的数值取代掉:

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

注意:与大多数其它集合的方法不同,transform 会修改集合本身。如果你希望创建新集合,就改用 map 方法。

unique() {#collection-method}

unique 方法返回集合中所有唯一的项目:

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

排序过的集合保有原来的数组键。在这个例子中我们用了 values 方法重设键为连续的数字索引。

当处理内嵌的数组或对象,你可以指定用来决定唯一性的键:

  1. $collection = collect([
  2. ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
  3. ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
  4. ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
  5. ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
  6. ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
  7. ]);
  8. $unique = $collection->unique('brand');
  9. $unique->values()->all();
  10. /*
  11. [
  12. ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
  13. ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
  14. ]
  15. */

你可以传入自己的回调函数来决定项目的唯一性:

  1. $unique = $collection->unique(function ($item) {
  2. return $item['brand'].$item['type'];
  3. });
  4. $unique->values()->all();
  5. /*
  6. [
  7. ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
  8. ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
  9. ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
  10. ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
  11. ]
  12. */

values() {#collection-method}

返回「键」重新被设为「连续整数」的新集合:

  1. $collection = collect([
  2. 10 => ['product' => 'Desk', 'price' => 200],
  3. 11 => ['product' => 'Desk', 'price' => 200]
  4. ]);
  5. $values = $collection->values();
  6. $values->all();
  7. /*
  8. [
  9. 0 => ['product' => 'Desk', 'price' => 200],
  10. 1 => ['product' => 'Desk', 'price' => 200],
  11. ]
  12. */

where() {#collection-method}

以一对指定的「键/数值」筛选集合:

  1. $collection = collect([
  2. ['product' => 'Desk', 'price' => 200],
  3. ['product' => 'Chair', 'price' => 100],
  4. ['product' => 'Bookcase', 'price' => 150],
  5. ['product' => 'Door', 'price' => 100],
  6. ]);
  7. $filtered = $collection->where('price', 100);
  8. $filtered->all();
  9. /*
  10. [
  11. ['product' => 'Chair', 'price' => 100],
  12. ['product' => 'Door', 'price' => 100],
  13. ]
  14. */

以严格比对检查数值。使用 whereLoose 方法以宽松比对进行筛选。

whereLoose() {#collection-method}

这个方法与 where 方法有着一样的形式;但是会以「宽松」比对来比对数值:

zip() {#collection-method}

zip 方法将集合与指定数组同样索引的值合并在一起:

  1. $collection = collect(['Chair', 'Desk']);
  2. $zipped = $collection->zip([100, 200]);
  3. $zipped->all();
  4. // [['Chair', 100], ['Desk', 200]]

{note} 欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创开源社区。

转载请注明:本文档由 Laravel China 社区 [laravel-china.org] 组织翻译。

文档永久地址: http://d.laravel-china.org