集合


1、简介

Illuminate\Support\Collection 类为处理数组数据提供了平滑、方便的封装。例如,查看下面的代码,我们使用辅助函数 collect 创建一个新的集合实例,为每一个元素运行 strtoupper 函数,然后移除所有空元素:

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

正如你所看到的,Collection 类允许你使用方法链对底层数组执行匹配和减少操作,通常,没个 Collection 方法都会返回一个新的 Collection 实例。

2、创建集合

正如上面所提到的,辅助函数 collect 为给定数组返回一个新的 Illuminate\Support\Collection 实例,所以,创建集合很简单:

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

默认情况下,Eloquent模型的集合总是返回 Collection 实例,此外,不管是在何处,只要方法都可以自由使用Collection类。

3、集合方法

本文档接下来的部分我们将会讨论 Collection 类上每一个有效的方法,所有这些方法都可以以方法链的方式平滑的操作底层数组。此外,几乎每个方法返回一个新的 Collection 实例,允许你在必要的时候保持原来的集合备份。

all()

all 方法简单返回集合表示的底层数组:

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

avg()

avg方法返回所有集合项的平均值:

  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. $collection->avg('pages');
  5. // 636

chunk()

chunk 方法将一个集合分割成多个小尺寸的小集合:

  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()

collapse 方法将一个多维数组集合收缩成一个一维数组:

  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()

contains 方法判断集合是否包含一个给定项:

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

你还可以传递一个键值对到 contains 方法,这将会判断给定键值对是否存在于集合中:

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

最后,你还可以传递一个回调到 contains 方法来执行自己的真实测试:

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

count()

count 方法返回集合中所有项的数目:

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

diff()

diff 方法将集合和另一个集合或原生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()

each 方法迭代集合中的数据项并传递每个数据项到给定回调:

  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()

every 方法创建一个包含数组第 n-th 个元素的新集合:

  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()

except 方法返回集合中除了指定键的所有集合项:

  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()

filter 方法通过给定回调过滤集合,只有通过给定测试的数据项才会保留下来:

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

filter 相对的方法是reject

first()

first 方法返回通过测试集合的第一个元素:

  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()

flatten 方法将多维度的集合变成一维的:

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

flip()

flip 方法将集合的键值做交换:

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

forget()

forget 方法通过键从集合中移除数据项:

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

注意:不同于大多数的集合方法,forget 不返回新的修改过的集合;它只修改所调用的集合。

forPage()

forPage 方法返回新的包含给定页数数据项的集合:

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

该方法需要传入页数和每页显示数目参数。

get()

get 方法返回给定键的数据项,如果不存在,返回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. // default-value

groupBy()

groupBy 方法通过给定键分组集合数据项:

  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.  
  7. $grouped = $collection->groupBy('account_id');
  8.  
  9. $grouped->toArray();
  10.  
  11. /*
  12. [
  13. 'account-x10' => [
  14. ['account_id' => 'account-x10', 'product' => 'Chair'],
  15. ['account_id' => 'account-x10', 'product' => 'Bookcase'],
  16. ],
  17. 'account-x11' => [
  18. ['account_id' => 'account-x11', 'product' => 'Desk'],
  19. ],
  20. ]
  21. */

除了传递字符串key,还可以传递一个回调,回调应该返回分组后的值:

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

has()

has 方法判断给定键是否在集合中存在:

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

implode()

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()

intersect 方法返回两个集合的交集:

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

正如你所看到的,结果集合只保持原来集合的键。

isEmpty()

如果集合为空的话 isEmpty 方法返回 true;否则返回 false

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

keyBy()

将指定键的值作为集合的键:

  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()

keys 方法返回所有集合的键:

  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()

last 方法返回通过测试的集合的最后一个元素:

  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()

map 方法遍历集合并传递每个值给给定回调。该回调可以修改数据项并返回,从而生成一个新的经过修改的集合:

  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()

max 方法返回集合中最大值:

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

merge()

merge 方法合并给定数组到集合。该数组中的任何字符串键匹配集合中的字符串键的将会重写集合中的值:

  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()

min 方法返回集合中的最小值:

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

only()

only 方法返回集合中指定键的集合项:

  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()

pluck 方法为给定键获取所有集合值:

  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()

pop 方法移除并返回集合中最后面的数据项:

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

prepend()

prepend 方法添加数据项到集合开头:

  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()

pull 方法通过键从集合中移除并返回数据项:

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

push()

push 方法附加数据项到集合结尾:

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

put()

put 方法在集合中设置给定键和值:

  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()

random 方法从集合中返回随机数据项:

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

你可以传递一个整型数据到 random 函数,如果该整型数值大于1,将会返回一个集合:

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

reduce()

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()

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]

reduce 方法相对的方法是filter方法。

reverse()

reverse 方法将集合数据项的顺序颠倒:

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

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. // 2

shift()

shift 方法从集合中移除并返回第一个数据项:

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

shuffle()

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()

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()

sort 方法对集合进行排序:

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

排序后的集合保持原来的数组键,在本例中我们使用 values 方法重置键为连续编号索引。

要为嵌套集合和对象排序,查看 sortBy和 sortByDesc 方法。

如果你需要更加高级的排序,你可以使用自己的算法传递一个回调给 sort 方法。参考 PHP 官方文档关于 usort 的说明,sort 方法底层正是调用了该方法。

sortBy()

sortBy方法通过给定键对集合进行排序:

  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()

该方法和 sortBy 用法相同,不同之处在于按照相反顺序进行排序。

splice()

splice 方法在从给定位置开始移除并返回数据项切片:

  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()

sum 方法返回集合中所有数据项的和:

  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()

take方法使用指定数目的数据项返回一个新的集合:

  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()

toArray 方法将集合转化为一个原生的 PHP 数组。如果集合的值是 Eloquent 模型,该模型也会被转化为数组:

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

注意:toArray 还将所有嵌套对象转化为数组。如果你想要获取底层数组,使用 all 方法。

toJson()

toJson 方法将集合转化为JSON:

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

transform()

transform 方法迭代集合并对集合中每个数据项调用给定回调。集合中的数据项将会被替代成从回调中返回的值:

  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()

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()

values 方法使用重置为连续整型数字的键返回新的集合:

  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()

where 方法通过给定键值对过滤集合:

  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. */

检查数据项值时 where 方法使用严格条件约束。使用whereLoose方法过滤松散约束。

whereLoose()

该方法和 where 使用方法相同,不同之处在于 whereLoose 在比较值的时候使用松散约束。

zip()

zip 方法在于集合的值相应的索引处合并给定数组的值:

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