# 集合

## 简介

`Illuminate\Support\Collection` 类提供了一个更具可读性和更便于处理数组数据的封装。具体请查看下方示例代码。我们使用 `collect`辅助函数从数组中创建一个新的集合实例，对其中每一个元素执行`strtoupper` 函数之后再删除所有的空元素：

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

### 创建集合

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

### 扩展集合

``````use Illuminate\Support\Collection;
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']``````

## 方法列表

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

`all` 方法返回代表集合的底层数组：

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

// [1, 2, 3]``````

#### `average()` {#collection-method}

`avg` 方法的别名。

#### `avg()` {#collection-method}

`avg` 方法返回指定键的 平均值

``````\$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');

// 20

\$average = collect([1, 1, 2, 4])->avg();

// 2``````

#### `chunk()` {#collection-method}

`chunk` 方法把集合分割成多个指定大小的较小集合：

``````\$collection = collect([1, 2, 3, 4, 5, 6, 7]);

\$chunks = \$collection->chunk(4);

\$chunks->toArray();

// [[1, 2, 3, 4], [5, 6, 7]]``````

``````@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()` {#collection-method}

`collapse` 方法把一个多数组集合平铺为单个扁平的集合：

``````\$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()` {#collection-method}

`combine` 方法将一个集合的值作为键，与另一个数组或集合的值进行结合：

``````\$collection = collect(['name', 'age']);

\$combined = \$collection->combine(['George', 29]);

\$combined->all();

// ['name' => 'George', 'age' => 29]``````

#### `collect()` {#collection-method}

`collect` 方法返回一个包含当前集合所含元素的新 `Collection` 实例：

``````\$collectionA = collect([1, 2, 3]);

\$collectionB = \$collectionA->collect();

\$collectionB->all();

// [1, 2, 3]``````

`collect` 方法从根本上对将 懒集合 转换为标准 `Collection` 实例有用:

``````\$lazyCollection = LazyCollection::make(function () {
yield 1;
yield 2;
yield 3;
});

\$collection = \$lazyCollection->collect();

get_class(\$collection);

// 'Illuminate\Support\Collection'

\$collection->all();

// [1, 2, 3]``````

{提示} 当你有个 `Enumerable` 实例并需要一个非懒集合实例时， `collect` 方法相当有用。由于 `collect()``Enumerable` 契约的一部分，你可以安全地使用它以获取一个 `Collection` 实例。

#### `concat()` {#collection-method}

`concat` 方法在集合的末端附加指定的 `数组` 或集合值：

``````\$collection = collect(['John Doe']);

\$concatenated = \$collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);

\$concatenated->all();

// ['John Doe', 'Jane Doe', 'Johnny Doe']``````

#### `contains()` {#collection-method}

`contains` 方法检查集合有否包含指定的元素：

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

\$collection->contains('Desk');

// true

\$collection->contains('New York');

// false``````

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

\$collection->contains('product', 'Bookcase');

// false``````

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

\$collection->contains(function (\$value, \$key) {
return \$value > 5;
});

// false``````

`contains` 方法用“松散”比较检查元素值，意味着整数值的字符串会被视同等值的整数。用 `containsStrict` 方法使用“严格”比较过滤。

#### `count()` {#collection-method}

`count` 方法返回这个集合内集合项的总数量：

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

\$collection->count();

// 4``````

#### `countBy()` {#collection-method}

`countBy` 方法计算集合中每个值的出现次数。默认情况下，该方法计算每个元素的出现次数：

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

\$counted = \$collection->countBy();

\$counted->all();

// [1 => 1, 2 => 3, 3 => 1]``````

``````\$collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']);

\$counted = \$collection->countBy(function (\$email) {
return substr(strrchr(\$email, "@"), 1);
});

\$counted->all();

// ['gmail.com' => 2, 'yahoo.com' => 1]``````

#### `crossJoin()` {#collection-method}

`crossJoin` 方法交叉连接指定数组或集合的值，返回所有可能排列的笛卡尔积:

``````\$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()` {#collection-method}

`dd` 方法用于打印集合元素并中断脚本执行：

``````\$collection = collect(['John Doe', 'Jane Doe']);

\$collection->dd();

/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/``````

#### `diff()` {#collection-method}

`diff` 方法将集合与其它集合或者 PHP 数组进行值的比较。然后返回原集合中存在而指定集合中不存在的值：

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

\$diff = \$collection->diff([2, 4, 6, 8]);

\$diff->all();

// [1, 3, 5]``````

#### `diffAssoc()` {#collection-method}

`diffAssoc` 方法与另外一个集合或基于 PHP 数组的键 / 值对（`keys and values`）进行比较。这个方法将会返回原集合不存在于指定集合的键 / 值对：

``````\$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()` {#collection-method}

`diffKeys`方法和另外一个集合或 PHP 数组的键（`keys`）进行比较，然后返回原集合中存在而指定集合中不存在键所对应的键 / 值对：

``````\$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()` {#collection-method}

`dump` 方法用于打印集合项：

``````\$collection = collect(['John Doe', 'Jane Doe']);

\$collection->dump();

/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/``````

#### `duplicates()` {#collection-method}

`duplicates` 方法从集合中检索并返回重复的值：

``````\$collection = collect(['a', 'b', 'a', 'c', 'b']);

\$collection->duplicates();

// [2 => 'a', 4 => 'b']``````

``````\$employees = collect([
['email' => 'abigail@example.com', 'position' => 'Developer'],
['email' => 'james@example.com', 'position' => 'Designer'],
['email' => 'victoria@example.com', 'position' => 'Developer'],
])

\$employees->duplicates('position');

// [2 => 'Developer']``````

#### `each()` {#collection-method}

`each` 方法用于循环集合项并将其传递到回调函数中：

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

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

#### `eachSpread()` {#collection-method}

`eachSpread` 方法用于循环集合项，将每个嵌套集合项的值传递给回调函数：

``````\$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);

//
});``````

``````\$collection->eachSpread(function (\$name, \$age) {
return false;
});``````

#### `every()` {#collection-method}

`every` 方法可用于验证集合中的每一个元素是否通过指定的条件测试：

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

// false``````

\$collection = collect([]);

``````\$collection->every(function (\$value, \$key) {
return \$value > 2;
});

// true``````

#### `except()` {#collection-method}

`except` 方法返回集合中除了指定键之外的所有集合项：

``````\$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);

\$filtered = \$collection->except(['price', 'discount']);

\$filtered->all();

// ['product_id' => 1]``````

`except` 对应的是 only 方法。

#### `filter()` {#collection-method}

`filter` 方法使用给定的回调函数过滤集合，只保留那些通过指定条件测试的集合项：

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

\$filtered = \$collection->filter(function (\$value, \$key) {
return \$value > 2;
});

\$filtered->all();

// [3, 4]``````

``````\$collection = collect([1, 2, 3, null, false, '', 0, []]);

\$collection->filter()->all();

// [1, 2, 3]``````

`filter` 对应的是 reject 方法。

#### `first()` {#collection-method}

`first` 方法返回集合中通过指定条件测试的第一个元素：

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

// 3``````

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

``````\$collection->firstWhere('age', '>=', 18);

// ['name' => 'Diego', 'age' => 23]``````

where 方法一样，你可以将一个参数传递给 `firstWhere` 方法。在这种情况下， `firstWhere` 方法将返回指定键的值为「真」的第一个集合项：

``````\$collection->firstWhere('age');

// ['name' => 'Linda', 'age' => 14]``````

#### `flatMap()`

`flatMap` 方法遍历集合并将其中的每个值传递到给定的回调函数。可以通过回调函数修改集合项并返回它们，从而形成一个被修改过的新集合。然后，集合转化的数组是同级的：

``````\$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` 方法将多维集合转为一维集合：

``````\$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);

\$flattened = \$collection->flatten();

\$flattened->all();

// ['taylor', 'php', 'javascript'];``````

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

#### `flip()`

`flip` 方法将集合的键和对应的值进行互换：

``````\$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

\$flipped = \$collection->flip();

\$flipped->all();

// ['taylor' => 'name', 'laravel' => 'framework']``````

#### `forget()`

`forget` 方法将通过指定的键来移除集合中对应的内容：

``````\$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

\$collection->forget('name');

\$collection->all();

// ['framework' => 'laravel']``````

#### `forPage()`

`forPage` 方法返回一个含有指定页码数集合项的新集合。这个方法接受页码数作为其第一个参数，每页显示的项数作为其第二个参数：

``````\$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``````

``````\$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

\$value = \$collection->get('foo', 'default-value');

// default-value``````

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

// default-value``````

#### `groupBy()`

`groupBy` 方法根据指定键对集合项进行分组：

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

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

``````\$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`方法用于合并集合项。其参数取决于集合项的类型。如果集合包含数组或对象，你应该传递你希望合并的属性的键，以及你希望放在值之间用来「拼接」的字符串：

``````\$collection = collect([
['account_id' => 1, 'product' => 'Desk'],
['account_id' => 2, 'product' => 'Chair'],
]);

\$collection->implode('product', ', ');

// Desk, Chair``````

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

// '1-2-3-4-5'``````

#### `intersect()` {#collection-method}

`intersect` 方法从原集合中移除在指定 `array` 或集合中不存在的值。生成的集合将会保留原集合的键：

``````\$collection = collect(['Desk', 'Sofa', 'Chair']);

\$intersect = \$collection->intersect(['Desk', 'Chair', 'Bookcase']);

\$intersect->all();

// [0 => 'Desk', 2 => 'Chair']``````

#### `intersectByKeys()` {#collection-method}

`intersectByKeys` 方法从原集合中移除在指定 `array` 或集合中不存在的任何键：

``````\$collection = collect([
'serial' => 'UX301', 'type' => 'screen', 'year' => 2009
]);

\$intersect = \$collection->intersectByKeys([
'reference' => 'UX404', 'type' => 'tab', 'year' => 2011
]);

\$intersect->all();

// ['type' => 'screen', 'year' => 2009]``````

#### `isEmpty()` {#collection-method}

``````collect([])->isEmpty();

// true``````

#### `isNotEmpty()` {#collection-method}

``````collect([])->isNotEmpty();

// false``````

#### `join()` {#collection-method}

`join` 方法会将集合中的值用字符串连接：

``````collect(['a', 'b', 'c'])->join(', '); // 'a, b, c'
collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'
collect(['a', 'b'])->join(', ', ' and '); // 'a and b'
collect(['a'])->join(', ', ' and '); // 'a'
collect([])->join(', ', ' and '); // ''``````

#### `keyBy()` {#collection-method}

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

``````\$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()` {#collection-method}

`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()` {#collection-method}

`last` 方法返回集合中通过指定条件测试的最后一个元素：

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

// 2``````

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

// 4``````

#### `map()` {#collection-method}

`map` 方法遍历集合并将每一个值传入给定的回调函数。该回调函数可以任意修改集合项并返回，从而生成被修改过集合项的新集合：

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

\$multiplied = \$collection->map(function (\$item, \$key) {
return \$item * 2;
});

\$multiplied->all();

// [2, 4, 6, 8, 10]``````

#### `mapInto()` {#collection-method}

`mapInto()` 方法可以迭代集合，通过将值传递给构造函数来创建给定类的新实例：

``````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()` {#collection-method}

`mapSpread` 方法可以迭代集合，将每个嵌套项值给指定的回调函数。该回调函数可以自由修改该集合项并返回，从而生成被修改过集合项的新集合：

``````\$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()` {#collection-method}

`mapToGroups` 方法通过给定的回调函数对集合项进行分组。该回调函数应该返回一个包含单个键 / 值对的关联数组，从而生成一个分组值的新集合：

``````\$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()` {#collection-method}

`mapWithKeys` 方法遍历集合并将每个值传入给定的回调函数。该回调函数将返回一个包含单个键 / 值对的关联数组：

``````\$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` 方法将合并指定的数组或集合到原集合。如果给定的集合项的字符串键与原集合中的字符串键相匹配，则指定集合项的值将覆盖原集合的值：

``````\$collection = collect(['product_id' => 1, 'price' => 100]);

\$merged = \$collection->merge(['price' => 200, 'discount' => false]);

\$merged->all();

// ['product_id' => 1, 'price' => 200, 'discount' => false]``````

``````\$collection = collect(['Desk', 'Chair']);

\$merged = \$collection->merge(['Bookcase', 'Door']);

\$merged->all();

// ['Desk', 'Chair', 'Bookcase', 'Door']``````

#### `mergeRecursive()`

`mergeRecursive`方法以递归的形式合并给定的数组或集合到原集合中，如果给定集合项的字符串键与原集合的字符串键一致，则会将给定的集合项的值以递归的形式合并到原集合的相同键中。

``````\$collection = collect(['product_id' => 1, 'price' => 100]);

\$merged = \$collection->mergeRecursive(['product_id' => 2, 'price' => 200, 'discount' => false]);

\$merged->all();

// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]``````

#### `min()`

`min` 方法返回指定键的最小值：

``````\$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');

// 10

\$min = collect([1, 2, 3, 4, 5])->min();

// 1``````

#### `mode()`

`mode` 方法返回指定键的 众数

``````\$mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');

// [10]

\$mode = collect([1, 1, 2, 4])->mode();

// [1]``````

#### `nth()`

`nth` 方法创建由每隔 n 个元素组成的一个新集合：

``````\$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);

\$collection->nth(4);

// ['a', 'e']``````

``````\$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` 对应的是 except 方法。

#### `pad()`

`pad` 方法将使用给定的值填充数组，直到数组达到指定的大小。该方法的行为与 array_pad PHP 函数功能类似。

``````\$collection = collect(['A', 'B', 'C']);

\$filtered->all();

// ['A', 'B', 'C', 0, 0]

\$filtered->all();

// [0, 0, 'A', 'B', 'C']``````

#### `partition()`

`partition` 方法可以和 PHP 函数中的 `list` 结合使用，用来分开通过指定条件的元素以及那些不通过指定条件的元素：

``````\$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` 方法传入一个回调函数并返回结果：

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

\$piped = \$collection->pipe(function (\$collection) {
return \$collection->sum();
});

// 6``````

#### `pluck()`

`pluck` 方法可以获取集合中指定键对应的所有值：

``````\$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);

\$plucked = \$collection->pluck('name');

\$plucked->all();

// ['Desk', 'Chair']``````

``````\$plucked = \$collection->pluck('name', 'product_id');

\$plucked->all();

// ['prod-100' => 'Desk', 'prod-200' => 'Chair']``````

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

``````\$collection = collect(['one' => 1, 'two' => 2]);

\$collection->prepend(0, 'zero');

\$collection->all();

// ['zero' => 0, 'one' => 1, 'two' => 2]``````

#### `pull()`

`pull` 方法把指定键对应的值从集合中移除并返回：

``````\$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` 方法在集合内设置给定的键值对：

``````\$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)``````

``````\$random = \$collection->random(3);

\$random->all();

// [2, 4, 5] - (retrieved randomly)``````

#### `reduce()` {#collection-method}

`reduce` 方法将每次迭代的结果传递给下一次迭代直到集合减少为单个值：

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

\$total = \$collection->reduce(function (\$carry, \$item) {
return \$carry + \$item;
});

// 6``````

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

// 10``````

#### `reject()` {#collection-method}

`reject` 方法使用指定的回调函数过滤集合。如果回调函数返回 true 就会把对应的集合项从集合中移除：

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

\$filtered = \$collection->reject(function (\$value, \$key) {
return \$value > 2;
});

\$filtered->all();

// [1, 2]``````

`reject` 方法对应的是 `filter` 方法。

#### `replace()` {#collection-method}

`replace` 方法类似于 `merge` ；但是，不仅可以覆盖匹配到的相同字符串键的集合项，而且也可以覆盖数字键的集合项：

``````\$collection = collect(['Taylor', 'Abigail', 'James']);

\$replaced = \$collection->replace([1 => 'Victoria', 3 => 'Finn']);

\$replaced->all();

// ['Taylor', 'Victoria', 'James', 'Finn']``````

#### `replaceRecursive()` {#collection-method}

``````\$collection = collect(['Taylor', 'Abigail', ['James', 'Victoria', 'Finn']]);

\$replaced = \$collection->replaceRecursive(['Charlie', 2 => [1 => 'King']]);

\$replaced->all();

// ['Charlie', 'Abigail', ['James', 'King', 'Finn']]``````

#### `reverse()` {#collection-method}

`reverse` 方法用来倒转集合项的顺序，并保留原始的键：

``````\$collection = collect(['a', 'b', 'c', 'd', 'e']);

\$reversed = \$collection->reverse();

\$reversed->all();

/*
[
4 => 'e',
3 => 'd',
2 => 'c',
1 => 'b',
0 => 'a',
]
*/``````

#### `search()` {#collection-method}

`search` 方法在集合中搜索给定的值并返回它的键。如果没有找到，则返回 `false`

``````\$collection = collect([2, 4, 6, 8]);

\$collection->search(4);

// 1``````

``````\$collection->search('4', true);

// false``````

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

// 2``````

#### `shift()` {#collection-method}

`shift` 方法移除并返回集合的第一个集合项：

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

\$collection->shift();

// 1

\$collection->all();

// [2, 3, 4, 5]``````

#### `shuffle()` {#collection-method}

`shuffle` 方法随机打乱集合项：

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

\$shuffled = \$collection->shuffle();

\$shuffled->all();

// [3, 2, 5, 1, 4] - (generated randomly)``````

#### `skip()` {#collection-method}

`skip` 方法返回除了给定的集合项数目的新集合：

``````\$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

\$collection = \$collection->skip(4);

\$collection->all();

// [5, 6, 7, 8, 9, 10]``````

#### `slice()` {#collection-method}

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

``````\$slice = \$collection->slice(4, 2);

\$slice->all();

// [5, 6]``````

#### `some()` {#collection-method}

`contains` 方法的别名。.

#### `sort()` {#collection-method}

`sort` 方法对集合进行排序。排序后的集合会保留原数组的键，所以在这个例子我们将使用 `values` 方法去把键重置为连续编号的索引：

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

\$sorted = \$collection->sort();

\$sorted->values()->all();

// [1, 2, 3, 4, 5]``````

#### `sortBy()` {#collection-method}

`sortBy` 方法将根据指定键对集合进行排序。排序后的集合会保留原始数组的键，所以在这个例子中我们使用 `values` 方法将键重置为连续编号的索引：

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

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

#### `sortDesc()` {#collection-method}

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

\$sorted = \$collection->sortDesc();

\$sorted->values()->all();

// [5, 4, 3, 2, 1]``````

#### `sortKeys()` {#collection-method}

`sortKeys` 方法通过底层关联数组的键来对集合进行排序：

``````\$collection = collect([
'id' => 22345,
'first' => 'John',
'last' => 'Doe',
]);

\$sorted = \$collection->sortKeys();

\$sorted->all();

/*
[
'first' => 'John',
'id' => 22345,
'last' => 'Doe',
]
*/``````

#### `splice()` {#collection-method}

`splice` 方法移除并返回指定索引开始的集合项片段：

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

\$chunk = \$collection->splice(2);

\$chunk->all();

// [3, 4, 5]

\$collection->all();

// [1, 2]``````

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

\$chunk = \$collection->splice(2, 1);

\$chunk->all();

// [3]

\$collection->all();

// [1, 2, 4, 5]``````

``````\$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()` {#collection-method}

`split` 方法将集合按照给定的值拆分：

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

\$groups = \$collection->split(3);

\$groups->toArray();

// [[1, 2], [3, 4], [5]]``````

#### `sum()` {#collection-method}

`sum` 方法返回集合内所有项的和：

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

// 15``````

``````\$collection = collect([
['name' => 'JavaScript: The Good Parts', 'pages' => 176],
['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);

\$collection->sum('pages');

// 1272``````

``````\$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()` {#collection-method}

`take` 方法返回给定数量项的新集合：

``````\$collection = collect([0, 1, 2, 3, 4, 5]);

\$chunk = \$collection->take(3);

\$chunk->all();

// [0, 1, 2]``````

``````\$collection = collect([0, 1, 2, 3, 4, 5]);

\$chunk = \$collection->take(-2);

\$chunk->all();

// [4, 5]``````

#### `tap()` {#collection-method}

`tap` 方法将给定的回调函数传入该集合，允许你在一个特定点「tap」集合，并在不影响集合本身的情况下对集合项执行某些操作：

``````collect([2, 4, 3, 1, 5])
->sort()
->tap(function (\$collection) {
Log::debug('Values after sorting', \$collection->values()->toArray());
})
->shift();

// 1``````

#### `times()` {#collection-method}

``````\$collection = Collection::times(10, function (\$number) {
return \$number * 9;
});

\$collection->all();

// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]``````

``````\$categories = Collection::times(3, function (\$number) {
return factory(Category::class)->create(['name' => "Category No. \$number"]);
});

\$categories->all();

/*
[
['id' => 1, 'name' => 'Category No. 1'],
['id' => 2, 'name' => 'Category No. 2'],
['id' => 3, 'name' => 'Category No. 3'],
]
*/``````

#### `toArray()` {#collection-method}

`toArray` 方法将集合转换成 PHP `array`。如果集合的值是 Eloquent 模型，那也会被转换成数组：

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

\$collection->toArray();

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

#### `toJson()` {#collection-method}

`toJson` 方法将集合转换成 JSON 字符串：

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

\$collection->toJson();

// '{"name":"Desk", "price":200}'``````

#### `transform()` {#collection-method}

`transform` 方法会遍历整个集合，并对集合中的每项都会调用其回调函数。集合中的值将被替换为回调函数返回的值：

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

\$collection->transform(function (\$item, \$key) {
return \$item * 2;
});

\$collection->all();

// [2, 4, 6, 8, 10]``````

#### `union()` {#collection-method}

`union` 方法将给定数组添加到集合中。如果给定的数组含有与原集合一样的键，则首选原始集合的值：

``````\$collection = collect([1 => ['a'], 2 => ['b']]);

\$union = \$collection->union([3 => ['c'], 1 => ['b']]);

\$union->all();

// [1 => ['a'], 2 => ['b'], 3 => ['c']]``````

#### `unique()` {#collection-method}

`unique` 方法返回集合中所有唯一项。返回的集合保留着原数组的键，所以在这个例子中，我们使用 `values` 方法把键重置为连续编号的索引：

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

\$unique = \$collection->unique();

\$unique->values()->all();

// [1, 2, 3, 4]``````

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

``````\$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` 方法在检查项目值时使用「宽松」模式比较，意味着具有整数值的字符串将被视为等于相同值的整数。你可以使用 `uniqueStrict` 方法做「严格」模式比较。

#### `unless()` {#collection-method}

`unless` 法当传入的第一个参数不为 `true` 的时候，将执行给定的回调函数：

``````\$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` 相反的方法, 请查看 `when` 方法。

#### `unlessEmpty()` {#collection-method}

`whenNotEmpty` 的别名方法。

#### `unlessNotEmpty()` {#collection-method}

`whenEmpty` 的别名方法。

#### `unwrap()` {#collection-method}

``````Collection::unwrap(collect('John Doe'));

// ['John Doe']

Collection::unwrap(['John Doe']);

// ['John Doe']

Collection::unwrap('John Doe');

// 'John Doe'``````

#### `values()` {#collection-method}

`values` 方法返回键被重置为连续编号的新集合：

``````\$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()` {#collection-method}

`when` 方法的第一个参数传入为 `true` 时，将执行给定的回调函数：

``````\$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` 相反的方法, 请查看 `unless`

#### `whenEmpty()` {#collection-method}

`whenEmpty` 方法是当集合为空时，将执行给定的回调函数：

``````\$collection = collect(['michael', 'tom']);

\$collection->whenEmpty(function (\$collection) {
});

\$collection->all();

// ['michael', 'tom']

\$collection = collect();

\$collection->whenEmpty(function (\$collection) {
});

\$collection->all();

\$collection = collect(['michael', 'tom']);

\$collection->whenEmpty(function (\$collection) {
}, function (\$collection) {
return \$collection->push('taylor');
});

\$collection->all();

// ['michael', 'tom', 'taylor']``````

`whenEmpty` 相反的方法, 请查看`whenNotEmpty`

#### `whenNotEmpty()` {#collection-method}

`whenNotEmpty` 方法当集合不为空时，将执行给定的回调函数：

``````\$collection = collect(['michael', 'tom']);

\$collection->whenNotEmpty(function (\$collection) {
});

\$collection->all();

\$collection = collect();

\$collection->whenNotEmpty(function (\$collection) {
});

\$collection->all();

// []

\$collection = collect();

\$collection->whenNotEmpty(function (\$collection) {
}, function (\$collection) {
return \$collection->push('taylor');
});

\$collection->all();

// ['taylor']``````

`whenNotEmpty` 相反的方法，请查看 `whenEmpty`

#### `where()` {#collection-method}

`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` 方法在检查集合项值时使用「宽松」模式比较，这意味着具有整数值的字符串会被认为等于相同值的整数。你可以使用 `whereStrict` 方法进行「严格」模式比较。

``````\$collection = collect([
['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
['name' => 'Sue', 'deleted_at' => null],
]);

\$filtered = \$collection->where('deleted_at', '!=', null);

\$filtered->all();

/*
[
['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
]
*/``````

#### `whereBetween()` {#collection-method}

`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()` {#collection-method}

`whereIn` 方法会根据包含给定数组的键 / 值对来过滤集合：

``````\$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' => 'Desk', 'price' => 200],
['product' => 'Bookcase', 'price' => 150],
]
*/``````

`whereIn` 方法在检查集合项值时使用「宽松」模式比较，这意味着具有整数值的字符串会被认为等于相同值的整数。你可以使用 `whereInStrict` 方法进行「严格」模式比较。

#### `whereInstanceOf()` {#collection-method}

`whereInstanceOf` 方法根据给定的类来过滤集合：

``````use App\User;
use App\Post;

\$collection = collect([
new User,
new User,
new Post,
]);

\$filtered = \$collection->whereInstanceOf(User::class);

\$filtered->all();

// [App\User, App\User]``````

#### `whereNotBetween()` {#collection-method}

`whereNotBetween` 方法在指定的范围内过滤集合：

``````\$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()` {#collection-method}

`whereNotIn` 方法根据未包含在指定数组的键 / 值对来对集合进行过滤：

``````\$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` 方法在检查集合项值时使用「宽松」模式比较，这意味着具有整数值的字符串会被认为等于相同值的整数。你可以使用 `whereNotInStrict` 方法进行「严格」模式比较。

#### `whereNotNull()` {#collection-method}

`whereNotNull` 方法筛选给定键不为 NULL 的项：

``````\$collection = collect([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
]);

\$filtered = \$collection->whereNotNull('name');

\$filtered->all();

/*
[
['name' => 'Desk'],
['name' => 'Bookcase'],
]
*/``````

#### `whereNull()` {#collection-method}

`whereNull` 方法筛选给定键为 NULL 的项：

``````\$collection = collect([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
]);

\$filtered = \$collection->whereNull('name');

\$filtered->all();

/*
[
['name' => null],
]
*/``````

#### `wrap()` {#collection-method}

``````\$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()` {#collection-method}

`zip` 方法将指定数组的值和相应索引的原集合的值合并在一起：

``````\$collection = collect(['Chair', 'Desk']);

\$zipped = \$collection->zip([100, 200]);

\$zipped->all();

// [['Chair', 100], ['Desk', 200]]``````

## 高阶消息传递

``````\$users = User::where('votes', '>', 500)->get();

\$users->each->markAsVip();``````

``````\$users = User::where('group', 'Development')->get();

## 懒集合

### 简介

``````use App\LogEntry;
use Illuminate\Support\LazyCollection;

LazyCollection::make(function () {
\$handle = fopen('log.txt', 'r');

while ((\$line = fgets(\$handle)) !== false) {
yield \$line;
}
})->chunk(4)->map(function (\$lines) {
return LogEntry::fromLines(\$lines);
})->each(function (LogEntry \$logEntry) {
// Process the log entry...
});``````

``````\$users = App\User::all()->filter(function (\$user) {
return \$user->id > 500;
});``````

``````\$users = App\User::cursor()->filter(function (\$user) {
return \$user->id > 500;
});

foreach (\$users as \$user) {
echo \$user->id;
}``````

### 懒集合

``````use Illuminate\Support\LazyCollection;

LazyCollection::make(function () {
\$handle = fopen('log.txt', 'r');

while ((\$line = fgets(\$handle)) !== false) {
yield \$line;
}
});``````

### The Enumerable Contract

`Collection` 类中几乎所有的方法在 `LazyCollection` 类中也能使用。这两个类都实现了 `Illuminate\Support\Enumerable` 契约，该契约定义了以下方法：

### 懒集合方法

#### `tapEach()` {#collection-method}

`each` 方法为集合中每一个集合项调用给定回调时，`tapEach` 方法仅调用给定回调，因为这些集合项正在逐个从列表中拉出：

``````\$lazyCollection = LazyCollection::times(INF)->tapEach(function (\$value) {
dump(\$value);
});

// Nothing has been dumped so far...

\$array = \$lazyCollection->take(3)->all();

// 1
// 2
// 3``````

#### `remember()` {#collection-method}

`remember`方法返回一个新的懒集合，这个集合已经记住了（缓存）已枚举所有的值，当再次枚举该集合时不会检索它们：

``````\$users = User::cursor()->remember();

// 没执行任何查询

\$users->take(5)->all();

// 执行了查询操作，并且前 5 个用户数据已经在数据库中查询完成

\$users->take(20)->all();

// 前 5 个用户数据在缓存中获取，其余 15 个用户数据在数据库中查询``````

《L04 微信小程序从零到发布》

《L03 构架 API 服务器》

1 个点赞 | 0 个回复 | 问答 | 课程版本 5.7

0 个点赞 | 7 个回复 | 问答 | 课程版本 5.5

0 个点赞 | 4 个回复 | 问答 | 课程版本 5.6

0 个点赞 | 3 个回复 | 问答 | 课程版本 5.8

0 个点赞 | 2 个回复 | 问答 | 课程版本 5.8