### 可用方法
在本文档的其余部分,我们将讨论`Collection`该类上可用的每种方法。请记住,所有这些方法都可以链接在一起,以流畅地操作基础数组。此外,几乎每个方法都返回一个新`Collection`实例,使您可以在必要时保留集合的原始副本。
您可以从此表中选择任何方法以查看其用法示例:
[所有](https://octobercms.com/docs/services/collections#method-all)[平均](https://octobercms.com/docs/services/collections#method-average)[平均](https://octobercms.com/docs/services/collections#method-avg)[大块](https://octobercms.com/docs/services/collections#method-chunk)[坍方](https://octobercms.com/docs/services/collections#method-collapse)[收藏](https://octobercms.com/docs/services/collections#method-collect)[结合](https://octobercms.com/docs/services/collections#method-combine)[康卡特](https://octobercms.com/docs/services/collections#method-concat)[包含](https://octobercms.com/docs/services/collections#method-contains)[containsStrict](https://octobercms.com/docs/services/collections#method-containsstrict)[计数](https://octobercms.com/docs/services/collections#method-count)[计数](https://octobercms.com/docs/services/collections#method-countBy)[交叉连接](https://octobercms.com/docs/services/collections#method-crossjoin)[dd](https://octobercms.com/docs/services/collections#method-dd)[差异](https://octobercms.com/docs/services/collections#method-diff)[diffAssoc](https://octobercms.com/docs/services/collections#method-diffassoc)[diffKeys](https://octobercms.com/docs/services/collections#method-diffkeys)[倾倒](https://octobercms.com/docs/services/collections#method-dump)[重复项](https://octobercms.com/docs/services/collections#method-duplicates)[严格重复](https://octobercms.com/docs/services/collections#method-duplicatesstrict)[每](https://octobercms.com/docs/services/collections#method-each)[过滤](https://octobercms.com/docs/services/collections#method-filter)[第一](https://octobercms.com/docs/services/collections#method-first)[首先在哪里](https://octobercms.com/docs/services/collections#method-first-where)[flatMap](https://octobercms.com/docs/services/collections#method-flatmap)[展平](https://octobercms.com/docs/services/collections#method-flatten)[翻转](https://octobercms.com/docs/services/collections#method-flip)[忘记](https://octobercms.com/docs/services/collections#method-forget)[forPage](https://octobercms.com/docs/services/collections#method-forpage)[得到](https://octobercms.com/docs/services/collections#method-get)[通过...分组](https://octobercms.com/docs/services/collections#method-groupby)[具有](https://octobercms.com/docs/services/collections#method-has)[内爆](https://octobercms.com/docs/services/collections#method-implode)[相交](https://octobercms.com/docs/services/collections#method-intersect)[相交键](https://octobercms.com/docs/services/collections#method-intersectbykeys)[是空的](https://octobercms.com/docs/services/collections#method-isempty)[isNotEmpty](https://octobercms.com/docs/services/collections#method-isnotempty)[加入](https://octobercms.com/docs/services/collections#method-join)[关键](https://octobercms.com/docs/services/collections#method-keyby)[键](https://octobercms.com/docs/services/collections#method-keys)[持续](https://octobercms.com/docs/services/collections#method-last)[地图](https://octobercms.com/docs/services/collections#method-map)[mapInto](https://octobercms.com/docs/services/collections#method-mapinto)[mapSpread](https://octobercms.com/docs/services/collections#method-mapspread)[mapToGroups](https://octobercms.com/docs/services/collections#method-maptogroups)[mapWithKeys](https://octobercms.com/docs/services/collections#method-mapwithkeys)[最高](https://octobercms.com/docs/services/collections#method-max)[中位数](https://octobercms.com/docs/services/collections#method-median)[合并](https://octobercms.com/docs/services/collections#method-merge)[mergeRecursive](https://octobercms.com/docs/services/collections#method-mergerecursive)[分](https://octobercms.com/docs/services/collections#method-min)[模式](https://octobercms.com/docs/services/collections#method-mode)[第n](https://octobercms.com/docs/services/collections#method-nth)[只要](https://octobercms.com/docs/services/collections#method-only)[垫](https://octobercms.com/docs/services/collections#method-pad)[划分](https://octobercms.com/docs/services/collections#method-partition)[管](https://octobercms.com/docs/services/collections#method-pipe)[采摘](https://octobercms.com/docs/services/collections#method-pluck)[流行音乐](https://octobercms.com/docs/services/collections#method-pop)[前置](https://octobercms.com/docs/services/collections#method-prepend)[拉](https://octobercms.com/docs/services/collections#method-pull)[推](https://octobercms.com/docs/services/collections#method-push)[放](https://octobercms.com/docs/services/collections#method-put)[随机](https://octobercms.com/docs/services/collections#method-random)[降低](https://octobercms.com/docs/services/collections#method-reduce)[拒绝](https://octobercms.com/docs/services/collections#method-reject)[更换](https://octobercms.com/docs/services/collections#method-replace)[replaceRecursive](https://octobercms.com/docs/services/collections#method-replacerecursive)[逆转](https://octobercms.com/docs/services/collections#method-reverse)[搜索](https://octobercms.com/docs/services/collections#method-search)[转移](https://octobercms.com/docs/services/collections#method-shift)[洗牌](https://octobercms.com/docs/services/collections#method-shuffle)[跳跃](https://octobercms.com/docs/services/collections#method-skip)[片](https://octobercms.com/docs/services/collections#method-slice)[一些](https://octobercms.com/docs/services/collections#method-some)[分类](https://octobercms.com/docs/services/collections#method-sort)[排序方式](https://octobercms.com/docs/services/collections#method-sortby)[sortByDesc](https://octobercms.com/docs/services/collections#method-sortbydesc)[sortKeys](https://octobercms.com/docs/services/collections#method-sortkeys)[sortKeysDesc](https://octobercms.com/docs/services/collections#method-sortkeysdesc)[拼接](https://octobercms.com/docs/services/collections#method-splice)[分裂](https://octobercms.com/docs/services/collections#method-split)[和](https://octobercms.com/docs/services/collections#method-sum)[采取](https://octobercms.com/docs/services/collections#method-take)[轻拍](https://octobercms.com/docs/services/collections#method-tap)[次](https://octobercms.com/docs/services/collections#method-times)[toArray](https://octobercms.com/docs/services/collections#method-toarray)[托森](https://octobercms.com/docs/services/collections#method-tojson)[转变](https://octobercms.com/docs/services/collections#method-transform)[联盟](https://octobercms.com/docs/services/collections#method-union)[独特](https://octobercms.com/docs/services/collections#method-unique)[uniqueStrict](https://octobercms.com/docs/services/collections#method-uniquestrict)[除非](https://octobercms.com/docs/services/collections#method-unless)[除非空](https://octobercms.com/docs/services/collections#method-unlessempty)[除非NotEmpty](https://octobercms.com/docs/services/collections#method-unlessnotempty)[拆开](https://octobercms.com/docs/services/collections#method-unwrap)[价值观](https://octobercms.com/docs/services/collections#method-values)[什么时候](https://octobercms.com/docs/services/collections#method-when)[whenEmpty](https://octobercms.com/docs/services/collections#method-whenempty)[whenNotEmpty](https://octobercms.com/docs/services/collections#method-whennotempty)[哪里](https://octobercms.com/docs/services/collections#method-where)[严格](https://octobercms.com/docs/services/collections#method-wherestrict)[之间](https://octobercms.com/docs/services/collections#method-wherebetween)[在哪里](https://octobercms.com/docs/services/collections#method-wherein)[whereInStrict](https://octobercms.com/docs/services/collections#method-whereinstrict)[whereInstanceOf](https://octobercms.com/docs/services/collections#method-whereinstanceof)[whereNotBetween](https://octobercms.com/docs/services/collections#method-wherenotbetween)[whereNotIn](https://octobercms.com/docs/services/collections#method-wherenotin)[WhereNotInStrict](https://octobercms.com/docs/services/collections#method-wherenotinstrict)[whereNotNull](https://octobercms.com/docs/services/collections#method-wherenotnull)[哪里空](https://octobercms.com/docs/services/collections#method-wherenull)[包](https://octobercms.com/docs/services/collections#method-wrap)[压缩](https://octobercms.com/docs/services/collections#method-zip)
### [](https://octobercms.com/docs/services/collections#method-listing)方法清单
#### [](https://octobercms.com/docs/services/collections#method-all)`all()`
该`all`方法仅返回由集合表示的基础数组:
~~~
$collection = new Collection([1, 2, 3]);
$collection->all();
// [1, 2, 3]
~~~
#### [](https://octobercms.com/docs/services/collections#method-average)`average()`
该[`avg`](https://octobercms.com/docs/services/collections#method-avg)方法的别名。
#### [](https://octobercms.com/docs/services/collections#method-avg)`avg()`
该`avg`方法返回给定键的[平均值](https://en.wikipedia.org/wiki/Average):
~~~
$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
// 20
$average = collect([1, 1, 2, 4])->avg();
// 2
~~~
#### [](https://octobercms.com/docs/services/collections#method-chunk)`chunk()`
该`chunk`方法将集合分成给定大小的多个较小的集合:
~~~
$collection = new Collection([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
~~~
当使用网格系统(例如[Bootstrap)](http://getbootstrap.com/css/#grid)时,此方法在[CMS页面中](https://octobercms.com/docs/cms/pages)特别有用。假设您要在网格中显示一组模型:[](http://getbootstrap.com/css/#grid)
~~~
{% for chunk in products.chunk(3) %}
<div class="row">
{% for product in chunk %}
<div class="col-xs-4">{{ product.name }}</div>
{% endfor %}
</div>
{% endfor %}
~~~
#### [](https://octobercms.com/docs/services/collections#method-collapse)`collapse()`
该`collapse`方法将数组的集合折叠为一个平面集合:
~~~
$collection = new Collection([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
$collapsed = $collection->collapse();
$collapsed->all();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
~~~
#### [](https://octobercms.com/docs/services/collections#method-combine)`combine()`
该`combine`方法将集合的值(作为键)与另一个数组或集合的值组合:
~~~
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]
~~~
#### [](https://octobercms.com/docs/services/collections#method-collect)`collect()`
该`collect`方法返回一个新`Collection`实例,其中包含当前集合中的项目:
~~~
$collectionA = collect([1, 2, 3]);
$collectionB = $collectionA->collect();
$collectionB->all();
// [1, 2, 3]
~~~
该`collect`方法主要用于将[惰性集合](https://octobercms.com/docs/services/collections#lazy-collections)转换为标准`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]
~~~
> **提示:**`collect`当您有一个实例`Enumerable`并且需要一个非延迟集合实例时,该方法特别有用。由于`collect()`是`Enumerable`合同的一部分,因此您可以放心地使用它来获取`Collection`实例。
#### [](https://octobercms.com/docs/services/collections#method-concat)`concat()`
该`concat`方法将给定`array`或集合值附加到集合的末尾:
~~~
$collection = collect(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
$concatenated->all();
// ['John Doe', 'Jane Doe', 'Johnny Doe']
~~~
#### [](https://octobercms.com/docs/services/collections#method-contains)`contains()`
该`contains`方法确定集合是否包含给定的项目:
~~~
$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
~~~
最后,您还可以将回调传递给该`contains`方法以执行您自己的真相测试:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$collection->contains(function ($value, $key) {
return $value > 5;
});
// false
~~~
该`contains`方法在检查项目值时使用“松散”比较,这意味着具有整数值的字符串将被视为等于相同值的整数。使用该[`containsStrict`](https://octobercms.com/docs/services/collections#method-containsstrict)方法使用“严格”比较进行过滤。
#### [](https://octobercms.com/docs/services/collections#method-containsstrict)`containsStrict()`
此方法与该方法具有相同的签名[`contains`](https://octobercms.com/docs/services/collections#method-contains);但是,使用“严格”比较来比较所有值。
#### [](https://octobercms.com/docs/services/collections#method-count)`count()`
该`count`方法返回集合中的项目总数:
~~~
$collection = new Collection([1, 2, 3, 4]);
$collection->count();
// 4
~~~
#### [](https://octobercms.com/docs/services/collections#method-countBy)`countBy()`
该`countBy`方法计算集合中值的出现次数。默认情况下,该方法计算每个元素的出现次数:
~~~
$collection = collect([1, 2, 2, 2, 3]);
$counted = $collection->countBy();
$counted->all();
// [1 => 1, 2 => 3, 3 => 1]
~~~
但是,您将回调传递给该`countBy`方法以通过自定义值对所有项目进行计数:
~~~
$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]
~~~
#### [](https://octobercms.com/docs/services/collections#method-crossjoin)`crossJoin()`
该`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'],
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-dd)`dd()`
该`dd`方法转储集合的项目并结束脚本的执行:
~~~
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/
~~~
如果不想停止执行脚本,请改用[`dump`](https://octobercms.com/docs/services/collections#method-dump)方法。
#### [](https://octobercms.com/docs/services/collections#method-diff)`diff()`
该`diff`方法将集合与另一个集合或纯PHP进行比较`array`:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]
~~~
#### [](https://octobercms.com/docs/services/collections#method-diffassoc)`diffAssoc()`
该`diffAssoc`方法`array`根据其键和值将集合与另一个集合或纯PHP进行比较。此方法将返回原始集合中给定集合中不存在的键/值对:
~~~
$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]
~~~
#### [](https://octobercms.com/docs/services/collections#method-diffkeys)`diffKeys()`
该`diffKeys`方法根据集合`array`的键将集合与另一个集合或纯PHP进行比较。此方法将返回原始集合中给定集合中不存在的键/值对:
~~~
$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]
~~~
#### [](https://octobercms.com/docs/services/collections#method-dump)`dump()`
该`dump`方法转储集合的项目:
~~~
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dump();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/
~~~
如果要在转储集合后停止执行脚本,请改用[`dd`](https://octobercms.com/docs/services/collections#method-dd)方法。
#### [](https://octobercms.com/docs/services/collections#method-duplicates)`duplicates()`
该`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']
~~~
#### [](https://octobercms.com/docs/services/collections#method-duplicatesstrict)`duplicatesStrict()`
此方法与该方法具有相同的签名[`duplicates`](https://octobercms.com/docs/services/collections#method-duplicates);但是,使用“严格”比较来比较所有值。
#### [](https://octobercms.com/docs/services/collections#method-each)`each()`
该`each`方法遍历集合中的项目并将每个项目传递给回调:
~~~
$collection->each(function ($item, $key) {
//
});
~~~
如果您想停止遍历所有项目,则可以`false`从回调中返回:
~~~
$collection->each(function ($item, $key) {
if (/* some condition */) {
return false;
}
});
~~~
#### [](https://octobercms.com/docs/services/collections#method-every)`every()`
该`every`方法创建一个由第n个元素组成的新集合:
~~~
$collection = new Collection(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->every(4);
// ['a', 'e']
~~~
您可以选择将offset作为第二个参数传递:
~~~
$collection->every(4, 1);
// ['b', 'f']
~~~
#### [](https://octobercms.com/docs/services/collections#method-filter)`filter()`
该`filter`方法通过给定的回调过滤集合,仅保留那些通过给定的真实性测试的项目:
~~~
$collection = new Collection([1, 2, 3, 4]);
$filtered = $collection->filter(function ($item) {
return $item > 2;
});
$filtered->all();
// [3, 4]
~~~
有关的反函数`filter`,请参见[拒绝](https://octobercms.com/docs/services/collections#method-reject)方法。
#### [](https://octobercms.com/docs/services/collections#method-first)`first()`
该`first`方法返回通过给定的真实性测试的集合中的第一个元素:
~~~
new Collection([1, 2, 3, 4])->first(function ($value, $key) {
return $value > 2;
});
// 3
~~~
您也可以`first`不带任何参数调用该方法以获取集合中的第一个元素。如果集合为空,`null`则返回:
~~~
new Collection([1, 2, 3, 4])->first();
// 1
~~~
#### [](https://octobercms.com/docs/services/collections#method-first-where)`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]
~~~
您也可以`firstWhere`使用运算符来调用该方法:
~~~
$collection->firstWhere('age', '>=', 18);
// ['name' => 'Diego', 'age' => 23]
~~~
像[where](https://octobercms.com/docs/services/collections#method-where)方法一样,您可以将一个参数传递给该`firstWhere`方法。在这种情况下,该`firstWhere`方法将返回给定项键值为“ truthy”的第一项:
~~~
$collection->firstWhere('age');
// ['name' => 'Linda', 'age' => 14]
~~~
#### [](https://octobercms.com/docs/services/collections#method-flatmap)`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'];
~~~
#### [](https://octobercms.com/docs/services/collections#method-flatten)`flatten()`
该`flatten`方法将多维集合展平为一个维:
~~~
$collection = new Collection(['name' => 'peter', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['peter', 'php', 'javascript'];
~~~
#### [](https://octobercms.com/docs/services/collections#method-flip)`flip()`
该`flip`方法将集合的键交换为其相应的值:
~~~
$collection = new Collection(['name' => 'peter', 'platform' => 'october']);
$flipped = $collection->flip();
$flipped->all();
// ['peter' => 'name', 'october' => 'platform']
~~~
#### [](https://octobercms.com/docs/services/collections#method-forget)`forget()`
该`forget`方法通过键将其从集合中移除:
~~~
$collection = new Collection(['name' => 'peter', 'platform' => 'october']);
$collection->forget('name');
$collection->all();
// ['platform' => 'october']
~~~
> **注意:**与大多数其他收集方法不同,`forget`它不返回新的修改后的收集;它修改了它被调用的集合。
#### [](https://octobercms.com/docs/services/collections#method-forpage)`forPage()`
该`forPage`方法返回一个新集合,其中包含将在给定页码上显示的项目:
~~~
$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9])->forPage(2, 3);
$collection->all();
// [4, 5, 6]
~~~
该方法需要页码和每页显示的项目数。
#### [](https://octobercms.com/docs/services/collections#method-get)`get()`
该`get`方法以给定的键返回该项目。如果密钥不存在,`null`则返回:
~~~
$collection = new Collection(['name' => 'peter', 'platform' => 'october']);
$value = $collection->get('name');
// peter
~~~
您可以选择将默认值作为第二个参数传递:
~~~
$collection = new Collection(['name' => 'peter', 'platform' => 'october']);
$value = $collection->get('foo', 'default-value');
// default-value
~~~
您甚至可以将回调作为默认值传递。如果指定的键不存在,则将返回回调结果:
~~~
$collection->get('email', function () {
return 'default-value';
});
// default-value
~~~
#### [](https://octobercms.com/docs/services/collections#method-groupby)`groupBy()`
该`groupBy`方法通过给定键将集合的项目分组:
~~~
$collection = new Collection([
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->toArray();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x10', 'product' => 'Chair'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
~~~
除了传递字符串外`key`,您还可以传递回调。回调应返回您希望通过以下方式键入组的值:
~~~
$grouped = $collection->groupBy(function ($item, $key) {
return substr($item['account_id'], -3);
});
$grouped->toArray();
/*
[
'x10' => [
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x10', 'product' => 'Chair'],
],
'x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-has)`has()`
该`has`方法确定集合中是否存在给定键:
~~~
$collection = new Collection(['account_id' => 1, 'product' => 'Desk']);
$collection->has('email');
// false
~~~
#### [](https://octobercms.com/docs/services/collections#method-implode)`implode()`
该`implode`方法将项目合并到一个集合中。其参数取决于集合中项目的类型。
如果集合包含数组或对象,则应传递希望加入的属性的键,以及希望在值之间放置的“ glue”字符串:
~~~
$collection = new Collection([
['account_id' => 1, 'product' => 'Chair'],
['account_id' => 2, 'product' => 'Desk'],
]);
$collection->implode('product', ', ');
// Chair, Desk
~~~
如果集合包含简单的字符串或数字值,则只需将“ glue”作为唯一的参数传递给方法:
~~~
new Collection([1, 2, 3, 4, 5])->implode('-');
// '1-2-3-4-5'
~~~
#### [](https://octobercms.com/docs/services/collections#method-intersect)`intersect()`
该`intersect`方法删除给定`array`或集合中不存在的所有值:
~~~
$collection = new Collection(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']
~~~
如您所见,生成的集合将保留原始集合的键。
#### [](https://octobercms.com/docs/services/collections#method-intersectbykeys)`intersectByKeys()`
该`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]
~~~
#### [](https://octobercms.com/docs/services/collections#method-isempty)`isEmpty()`
如果集合为空,则`isEmpty`返回该方法`true`;否则返回false。否则`false`返回:
~~~
new Collection([])->isEmpty();
// true
~~~
#### [](https://octobercms.com/docs/services/collections#method-isnotempty)`isNotEmpty()`
如果集合不为空,则`isNotEmpty`返回该方法`true`;否则返回false。否则,`false`返回:
~~~
collect([])->isNotEmpty();
// false
~~~
#### [](https://octobercms.com/docs/services/collections#method-join)`join()`
该`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 '); // ''
~~~
#### [](https://octobercms.com/docs/services/collections#method-keyby)`keyBy()`
通过给定的键为集合设置键:
~~~
$collection = new Collection([
['product_id' => 'prod-100', 'name' => 'chair'],
['product_id' => 'prod-200', 'name' => 'desk'],
]);
$keyed = $collection->keyBy('product_id');
$keyed->all();
/*
[
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Chair'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Desk'],
]
*/
~~~
如果多个项目具有相同的键,则只有最后一个将出现在新集合中。
您还可以传递自己的回调,该回调应通过以下方式返回值以键值集合:
~~~
$keyed = $collection->keyBy(function ($item) {
return strtoupper($item['product_id']);
});
$keyed->all();
/*
[
'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Chair'],
'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Desk'],
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-keys)`keys()`
该`keys`方法返回集合的所有键:
~~~
$collection = new Collection([
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Chair'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Desk'],
]);
$keys = $collection->keys();
$keys->all();
// ['prod-100', 'prod-200']
~~~
#### [](https://octobercms.com/docs/services/collections#method-last)`last()`
该`last`方法返回通过给定的真实性测试的集合中的最后一个元素:
~~~
new Collection([1, 2, 3, 4])->last(function ($key, $value) {
return $value < 3;
});
// 2
~~~
您也可以`last`不带任何参数的方法来获取集合中的最后一个元素。如果集合为空,则`null`返回。
~~~
new Collection([1, 2, 3, 4])->last();
// 4
~~~
#### [](https://octobercms.com/docs/services/collections#method-map)`map()`
该`map`方法遍历集合并将每个值传递给给定的回调。回调程序可以自由修改并返回它,从而形成一个新的修改后的集合:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]
~~~
> **注意:**与大多数其他收集方法一样,`map`返回一个新的收集实例。它不会修改调用的集合。如果要转换原始集合,请使用[`transform`](https://octobercms.com/docs/services/collections#method-transform)方法。
#### [](https://octobercms.com/docs/services/collections#method-mapinto)`mapInto()`
该`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')]
~~~
#### [](https://octobercms.com/docs/services/collections#method-mapspread)`mapSpread()`
该`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]
~~~
#### [](https://octobercms.com/docs/services/collections#method-maptogroups)`mapToGroups()`
该`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']
~~~
#### [](https://octobercms.com/docs/services/collections#method-mapwithkeys)`mapWithKeys()`
该`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',
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-max)`max()`
该`max`方法返回给定键的最大值:
~~~
$max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
// 20
$max = collect([1, 2, 3, 4, 5])->max();
// 5
~~~
#### [](https://octobercms.com/docs/services/collections#method-median)`median()`
该`median`方法返回给定键的[中间值](https://en.wikipedia.org/wiki/Median):
~~~
$median = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');
// 15
$median = collect([1, 1, 2, 4])->median();
// 1.5
~~~
#### [](https://octobercms.com/docs/services/collections#method-merge)`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']
~~~
#### [](https://octobercms.com/docs/services/collections#method-mergerecursive)`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]
~~~
#### [](https://octobercms.com/docs/services/collections#method-min)`min()`
该`min`方法返回给定键的最小值:
~~~
$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
// 10
$min = collect([1, 2, 3, 4, 5])->min();
// 1
~~~
#### [](https://octobercms.com/docs/services/collections#method-mode)`mode()`
该`mode`方法返回给定键的[模式值](https://en.wikipedia.org/wiki/Mode_(statistics)):
~~~
$mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');
// [10]
$mode = collect([1, 1, 2, 4])->mode();
// [1]
~~~
#### [](https://octobercms.com/docs/services/collections#method-nth)`nth()`
该`nth`方法创建一个由第n个元素组成的新集合:
~~~
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->nth(4);
// ['a', 'e']
~~~
您可以选择将偏移量作为第二个参数传递:
~~~
$collection->nth(4, 1);
// ['b', 'f']
~~~
#### [](https://octobercms.com/docs/services/collections#method-only)`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](https://octobercms.com/docs/services/collections#method-except)方法。
#### [](https://octobercms.com/docs/services/collections#method-pad)`pad()`
该`pad`方法将使用给定值填充数组,直到数组达到指定大小为止。此方法的行为类似于[array\_pad](https://secure.php.net/manual/en/function.array-pad.php)PHP函数。
要向左填充,应指定一个负数。如果给定大小的绝对值小于或等于数组的长度,则不会进行填充:
~~~
$collection = collect(['A', 'B', 'C']);
$filtered = $collection->pad(5, 0);
$filtered->all();
// ['A', 'B', 'C', 0, 0]
$filtered = $collection->pad(-5, 0);
$filtered->all();
// [0, 0, 'A', 'B', 'C']
~~~
#### [](https://octobercms.com/docs/services/collections#method-partition)`partition()`
该`partition`方法可以与`list`PHP函数结合使用,以将通过给定真值测试的元素与未通过的元素分开:
~~~
$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]
~~~
#### [](https://octobercms.com/docs/services/collections#method-pipe)`pipe()`
该`pipe`方法将集合传递给给定的回调并返回结果:
~~~
$collection = collect([1, 2, 3]);
$piped = $collection->pipe(function ($collection) {
return $collection->sum();
});
// 6
~~~
#### [](https://octobercms.com/docs/services/collections#method-pluck)`pluck()`
该`pluck`方法检索给定键的所有集合值:
~~~
$collection = new Collection([
['product_id' => 'prod-100', 'name' => 'Chair'],
['product_id' => 'prod-200', 'name' => 'Desk'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Chair', 'Desk']
~~~
您还可以指定希望如何对结果集合进行键控:
~~~
$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
~~~
#### [](https://octobercms.com/docs/services/collections#method-pop)`pop()`
该`pop`方法从集合中删除并返回最后一个项目:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$collection->pop();
// 5
$collection->all();
// [1, 2, 3, 4]
~~~
#### [](https://octobercms.com/docs/services/collections#method-prepend)`prepend()`
该`prepend`方法将一个项目添加到集合的开头:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$collection->prepend(0);
$collection->all();
// [0, 1, 2, 3, 4, 5]
~~~
#### [](https://octobercms.com/docs/services/collections#method-pull)`pull()`
该`pull`方法通过其键从集合中删除并返回一个项目:
~~~
$collection = new Collection(['product_id' => 'prod-100', 'name' => 'Desk']);
$collection->pull('name');
// 'Desk'
$collection->all();
// ['product_id' => 'prod-100']
~~~
#### [](https://octobercms.com/docs/services/collections#method-push)`push()`
该`push`方法将一个项目附加到集合的末尾:
~~~
$collection = new Collection([1, 2, 3, 4]);
$collection->push(5);
$collection->all();
// [1, 2, 3, 4, 5]
~~~
#### [](https://octobercms.com/docs/services/collections#method-put)`put()`
该`put`方法在集合中设置给定的键和值:
~~~
$collection = new Collection(['product_id' => 1, 'name' => 'Desk']);
$collection->put('price', 100);
$collection->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
~~~
#### [](https://octobercms.com/docs/services/collections#method-random)`random()`
该`random`方法从集合中返回一个随机项目:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$collection->random();
// 4 - (retrieved randomly)
~~~
您可以选择将整数传递给`random`。如果该整数大于`1`,则返回项目的集合:
~~~
$random = $collection->random(3);
$random->all();
// [2, 4, 5] - (retrieved randomly)
~~~
#### [](https://octobercms.com/docs/services/collections#method-reduce)`reduce()`
该`reduce`方法将集合简化为单个值,将每次迭代的结果传递到后续迭代中:
~~~
$collection = new Collection([1, 2, 3]);
$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
});
// 6
~~~
第`$carry`一次迭代的值为`null`:但是,您可以通过将第二个参数传递给来指定其初始值`reduce`:
~~~
$collection->reduce(function ($carry, $item) {
return $carry + $item;
}, 4);
// 10
~~~
#### [](https://octobercms.com/docs/services/collections#method-reject)`reject()`
该`reject`方法使用给定的回调过滤集合。回调应返回`true`希望从结果集合中删除的所有项目:
~~~
$collection = new Collection([1, 2, 3, 4]);
$filtered = $collection->reject(function ($item) {
return $item > 2;
});
$filtered->all();
// [1, 2]
~~~
有关`reject`方法的逆过程,请参见[`filter`](https://octobercms.com/docs/services/collections#method-filter)方法。
#### [](https://octobercms.com/docs/services/collections#method-replace)`replace()`
该`replace`方法的行为类似于`merge`;但是,除了使用字符串键覆盖匹配项之外,该`replace`方法还将覆盖集合中具有匹配数字键的项:
~~~
$collection = collect(['Taylor', 'Abigail', 'James']);
$replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']);
$replaced->all();
// ['Taylor', 'Victoria', 'James', 'Finn']
~~~
#### [](https://octobercms.com/docs/services/collections#method-replacerecursive)`replaceRecursive()`
此方法的工作方式与相似`replace`,但它将重现为数组并将相同的替换过程应用于内部值:
~~~
$collection = collect(['Taylor', 'Abigail', ['James', 'Victoria', 'Finn']]);
$replaced = $collection->replaceRecursive(['Charlie', 2 => [1 => 'King']]);
$replaced->all();
// ['Charlie', 'Abigail', ['James', 'King', 'Finn']]
~~~
#### [](https://octobercms.com/docs/services/collections#method-reverse)`reverse()`
该`reverse`方法反转集合项的顺序:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$reversed = $collection->reverse();
$reversed->all();
// [5, 4, 3, 2, 1]
~~~
#### [](https://octobercms.com/docs/services/collections#method-search)`search()`
该`search`方法在集合中搜索给定的值,如果找到,则返回其键。如果找不到该项目,`false`则返回。
~~~
$collection = new Collection([2, 4, 6, 8]);
$collection->search(4);
// 1
~~~
使用“松散”比较完成搜索。要使用严格比较,`true`请将第二个参数传递给该方法:
~~~
$collection->search('4', true);
// false
~~~
或者,您可以传递自己的回调来搜索通过真实性测试的第一项:
~~~
$collection->search(function ($item, $key) {
return $item > 5;
});
// 2
~~~
#### [](https://octobercms.com/docs/services/collections#method-shift)`shift()`
该`shift`方法从集合中删除并返回第一项:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$collection->shift();
// 1
$collection->all();
// [2, 3, 4, 5]
~~~
#### [](https://octobercms.com/docs/services/collections#method-shuffle)`shuffle()`
该`shuffle`方法随机地随机移动集合中的项目:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] (generated randomly)
~~~
#### [](https://octobercms.com/docs/services/collections#method-skip)`skip()`
该`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]
~~~
#### [](https://octobercms.com/docs/services/collections#method-slice)`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]
~~~
如果您想限制返回的切片的大小,请将所需的大小作为方法的第二个参数传递给:
~~~
$slice = $collection->slice(4, 2);
$slice->all();
// [5, 6]
~~~
返回的切片将默认保留键。如果您不想保留原始密钥,则可以使用该[`values`](https://octobercms.com/docs/services/collections#method-values)方法为它们重新编制索引。
#### [](https://octobercms.com/docs/services/collections#method-some)`some()`
该[`contains`](https://octobercms.com/docs/services/collections#method-contains)方法的别名。
#### [](https://octobercms.com/docs/services/collections#method-sort)`sort()`
该`sort`方法对集合进行排序:
~~~
$collection = new Collection([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]
~~~
排序的集合保留原始数组键。在此示例中,我们使用该[`values`](https://octobercms.com/docs/services/collections#method-values)方法将密钥重置为连续编号的索引。
有关对嵌套数组或对象的集合进行排序的信息,请参见[`sortBy`](https://octobercms.com/docs/services/collections#method-sortby)和[`sortByDesc`](https://octobercms.com/docs/services/collections#method-sortbydesc)方法。
如果您的排序需求更高级,则可以`sort`使用自己的算法将回调传递给。请参阅上的PHP文档[`usort`](http://php.net/manual/en/function.usort.php#refsect1-function.usort-parameters),这是集合的`sort`方法在后台调用的内容。
#### [](https://octobercms.com/docs/services/collections#method-sortby)`sortBy()`
该`sortBy`方法按给定键对集合进行排序:
~~~
$collection = new Collection([
['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],
]
*/
~~~
排序的集合保留原始数组键。在此示例中,我们使用该[`values`](https://octobercms.com/docs/services/collections#method-values)方法将密钥重置为连续编号的索引。
您还可以传递自己的回调以确定如何对集合值进行排序:
~~~
$collection = new Collection([
['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']],
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-sortbydesc)`sortByDesc()`
此方法与该方法具有相同的签名[`sortBy`](https://octobercms.com/docs/services/collections#method-sortby),但是将以相反的顺序对集合进行排序。
#### [](https://octobercms.com/docs/services/collections#method-sortkeys)`sortKeys()`
该`sortKeys`方法通过基础关联数组的键对集合进行排序:
~~~
$collection = collect([
'id' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeys();
$sorted->all();
/*
[
'first' => 'John',
'id' => 22345,
'last' => 'Doe',
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-sortkeysdesc)`sortKeysDesc()`
此方法与该方法具有相同的签名[`sortKeys`](https://octobercms.com/docs/services/collections#method-sortkeys),但是将以相反的顺序对集合进行排序。
#### [](https://octobercms.com/docs/services/collections#method-splice)`splice()`
该`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]
~~~
#### [](https://octobercms.com/docs/services/collections#method-splice)`splice()`
该`splice`方法删除并返回从指定索引处开始的项目切片:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2);
$chunk->all();
// [3, 4, 5]
$collection->all();
// [1, 2]
~~~
您可以传递第二个参数来限制结果块的大小:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 4, 5]
~~~
此外,您可以传递包含新项目的第三个参数来替换从集合中删除的项目:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$chunk = $collection->splice(2, 1, [10, 11]);
$chunk->all();
// [3]
$collection->all();
// [1, 2, 10, 11, 4, 5]
~~~
#### [](https://octobercms.com/docs/services/collections#method-split)`split()`
该`split`方法将集合分为给定数量的组:
~~~
$collection = collect([1, 2, 3, 4, 5]);
$groups = $collection->split(3);
$groups->toArray();
// [[1, 2], [3, 4], [5]]
~~~
#### [](https://octobercms.com/docs/services/collections#method-sum)`sum()`
该`sum`方法返回集合中所有项目的总和:
~~~
new Collection([1, 2, 3, 4, 5])->sum();
// 15
~~~
如果集合包含嵌套的数组或对象,则应传递一个键来确定要求和的值:
~~~
$collection = new Collection([
['name' => 'JavaScript: The Good Parts', 'pages' => 176],
['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);
$collection->sum('pages');
// 1272
~~~
另外,您可以传递自己的回调以确定汇总哪些集合值:
~~~
$collection = new Collection([
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$collection->sum(function ($product) {
return count($product['colors']);
});
// 6
~~~
#### [](https://octobercms.com/docs/services/collections#method-take)`take()`
该`take`方法返回具有指定数量的项目的新集合:
~~~
$collection = new Collection([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]
~~~
您还可以传递一个负整数以从集合的末尾获取指定数量的项目:
~~~
$collection = new Collection([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(-2);
$chunk->all();
// [4, 5]
~~~
#### [](https://octobercms.com/docs/services/collections#method-tap)`tap()`
该`tap`方法将集合传递给给定的回调,使您可以在特定位置“点击”集合,并在不影响集合本身的情况下对项目进行一些操作:
~~~
collect([2, 4, 3, 1, 5])
->sort()
->tap(function ($collection) {
Log::debug('Values after sorting', $collection->values()->toArray());
})
->shift();
// 1
~~~
#### [](https://octobercms.com/docs/services/collections#method-times)`times()`
静态`times`方法通过调用给定次数的回调来创建新集合:
~~~
$collection = Collection::times(10, function ($number) {
return $number * 9;
});
$collection->all();
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
~~~
与工厂结合以创建[Eloquent](https://octobercms.com/docs/%7B%7Bversion%7D%7D/eloquent)模型时,此方法很有用:
~~~
$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'],
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-toarray)`toArray()`
该`toArray`方法将集合转换为纯PHP`array`。如果集合的值是[数据库模型](https://octobercms.com/docs/database/model),则这些模型也将转换为数组:
~~~
$collection = new Collection(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/
~~~
> **注意:**`toArray`还将所有嵌套对象转换为数组。如果要按原样获取基础数组,请使用[`all`](https://octobercms.com/docs/services/collections#method-all)方法。
#### [](https://octobercms.com/docs/services/collections#method-tojson)`toJson()`
该`toJson`方法将集合转换为JSON:
~~~
$collection = new Collection(['name' => 'Desk', 'price' => 200]);
$collection->toJson();
// '{"name":"Desk","price":200}'
~~~
#### [](https://octobercms.com/docs/services/collections#method-transform)`transform()`
该`transform`方法遍历集合,并使用集合中的每个项目调用给定的回调。集合中的项目将由回调返回的值替换:
~~~
$collection = new Collection([1, 2, 3, 4, 5]);
$collection->transform(function ($item, $key) {
return $item * 2;
});
$collection->all();
// [2, 4, 6, 8, 10]
~~~
> **注意:**与大多数其他收集方法不同,`transform`修改收集本身。如果您想创建一个新的集合,请使用[`map`](https://octobercms.com/docs/services/collections#method-map)方法。
#### [](https://octobercms.com/docs/services/collections#method-union)`union()`
该`union`方法将给定数组添加到集合中。如果给定数组包含原始集合中已经存在的键,则首选原始集合的值:
~~~
$collection = collect([1 => ['a'], 2 => ['b']]);
$union = $collection->union([3 => ['c'], 1 => ['b']]);
$union->all();
// [1 => ['a'], 2 => ['b'], 3 => ['c']]
~~~
#### [](https://octobercms.com/docs/services/collections#method-unique)`unique()`
该`unique`方法返回集合中的所有唯一项。返回的集合保留原始数组键,因此在此示例中,我们将使用[`values`](https://octobercms.com/docs/services/collections#method-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`](https://octobercms.com/docs/services/collections#method-uniquestrict)方法使用“严格”比较进行过滤。
#### [](https://octobercms.com/docs/services/collections#method-uniquestrict)`uniqueStrict()`
此方法与该方法具有相同的签名[`unique`](https://octobercms.com/docs/services/collections#method-unique);但是,使用“严格”比较来比较所有值。
#### [](https://octobercms.com/docs/services/collections#method-unless)`unless()`
该`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`](https://octobercms.com/docs/services/collections#method-when)方法。
#### [](https://octobercms.com/docs/services/collections#method-unlessempty)`unlessEmpty()`
该[`whenNotEmpty`](https://octobercms.com/docs/services/collections#method-whennotempty)方法的别名。
#### [](https://octobercms.com/docs/services/collections#method-unlessnotempty)`unlessNotEmpty()`
该[`whenEmpty`](https://octobercms.com/docs/services/collections#method-whenempty)方法的别名。
#### [](https://octobercms.com/docs/services/collections#method-unwrap)`unwrap()`
静态`unwrap`方法在适用时从给定值返回集合的基础项:
~~~
Collection::unwrap(collect('John Doe'));
// ['John Doe']
Collection::unwrap(['John Doe']);
// ['John Doe']
Collection::unwrap('John Doe');
// 'John Doe'
~~~
#### [](https://octobercms.com/docs/services/collections#method-values)`values()`
该`values`方法返回一个新集合,其键重置为连续的整数:
~~~
$collection = new Collection([
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],
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-when)`when()`
`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`](https://octobercms.com/docs/services/collections#method-unless)方法。
#### [](https://octobercms.com/docs/services/collections#method-whenempty)`whenEmpty()`
`whenEmpty`当集合为空时,该方法将执行给定的回调:
~~~
$collection = collect(['michael', 'tom']);
$collection->whenEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// ['michael', 'tom']
$collection = collect();
$collection->whenEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// ['adam']
$collection = collect(['michael', 'tom']);
$collection->whenEmpty(function ($collection) {
return $collection->push('adam');
}, function ($collection) {
return $collection->push('taylor');
});
$collection->all();
// ['michael', 'tom', 'taylor']
~~~
有关的逆`whenEmpty`,请参见[`whenNotEmpty`](https://octobercms.com/docs/services/collections#method-whennotempty)方法。
#### [](https://octobercms.com/docs/services/collections#method-whennotempty)`whenNotEmpty()`
`whenNotEmpty`当集合不为空时,该方法将执行给定的回调:
~~~
$collection = collect(['michael', 'tom']);
$collection->whenNotEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// ['michael', 'tom', 'adam']
$collection = collect();
$collection->whenNotEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// []
$collection = collect();
$collection->whenNotEmpty(function ($collection) {
return $collection->push('adam');
}, function ($collection) {
return $collection->push('taylor');
});
$collection->all();
// ['taylor']
~~~
有关的逆`whenNotEmpty`,请参见[`whenEmpty`](https://octobercms.com/docs/services/collections#method-whenempty)方法。
#### [](https://octobercms.com/docs/services/collections#method-where)`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],
]
*/
~~~
该`where`方法在检查项目值时使用“松散”比较,这意味着具有整数值的字符串将被视为等于相同值的整数。使用该[`whereStrict`](https://octobercms.com/docs/services/collections#method-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'],
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-wherestrict)`whereStrict()`
此方法与该方法具有相同的签名[`where`](https://octobercms.com/docs/services/collections#method-where);但是,使用“严格”比较来比较所有值。
#### [](https://octobercms.com/docs/services/collections#method-wherebetween)`whereBetween()`
该`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],
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-wherein)`whereIn()`
该`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`](https://octobercms.com/docs/services/collections#method-whereinstrict)方法使用“严格”比较进行过滤。
#### [](https://octobercms.com/docs/services/collections#method-whereinstrict)`whereInStrict()`
此方法与该方法具有相同的签名[`whereIn`](https://octobercms.com/docs/services/collections#method-wherein);但是,使用“严格”比较来比较所有值。
#### [](https://octobercms.com/docs/services/collections#method-whereinstanceof)`whereInstanceOf()`
该`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]
~~~
#### [](https://octobercms.com/docs/services/collections#method-wherenotbetween)`whereNotBetween()`
该`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],
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-wherenotin)`whereNotIn()`
该`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`](https://octobercms.com/docs/services/collections#method-wherenotinstrict)方法使用“严格”比较进行过滤。
#### [](https://octobercms.com/docs/services/collections#method-wherenotinstrict)`whereNotInStrict()`
此方法与该方法具有相同的签名[`whereNotIn`](https://octobercms.com/docs/services/collections#method-wherenotin);但是,使用“严格”比较来比较所有值。
#### [](https://octobercms.com/docs/services/collections#method-wherenotnull)`whereNotNull()`
该`whereNotNull`方法过滤给定键不为null的项目:
~~~
$collection = collect([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
]);
$filtered = $collection->whereNotNull('name');
$filtered->all();
/*
[
['name' => 'Desk'],
['name' => 'Bookcase'],
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-wherenull)`whereNull()`
该`whereNull`方法过滤给定键为null的项目:
~~~
$collection = collect([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
]);
$filtered = $collection->whereNull('name');
$filtered->all();
/*
[
['name' => null],
]
*/
~~~
#### [](https://octobercms.com/docs/services/collections#method-wrap)`wrap()`
`wrap`如果适用,静态方法会将给定值包装在集合中:
~~~
$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']
~~~
#### [](https://octobercms.com/docs/services/collections#method-zip)`zip()`
该`zip`方法将给定数组的值与原始集合在相应索引处的值合并在一起:
~~~
$collection = collect(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]
~~~
- 基本说明
- 基本操作
- October cms 安装
- 后台控制器路径
- 图标
- 获取安装网上的插件/主题
- 插件构造器使用
- 定时任务
- October后台控制器
- vscode编辑器
- ajax操作
- 使用
- ajax更新组件
- ajax属性API
- JavaScript API
- ajax综合使用
- 主题
- 多语言主题
- 安装市场主题
- 主题程序处理
- 主题
- 页面
- 部件
- 布局
- 内容
- 组件
- 媒体
- 主题表单操作
- 表单使用
- 表单后端程序处理
- 插件
- 自定义插件
- 插件说明
- 插件导航条
- 插件数据库设置
- 插件的设置管理
- 插件的配置文件config
- 组件
- app服务
- app容器
- 扩展行为
- 缓存
- Collection类
- Lazy Collections
- Collection方法
- 助手函数
- 数组助手函数
- 路径助手函数
- 玄乐助手函数
- 其他助手函数
- 错误与记录
- 事件处理
- HTML页面
- 文件与目录操作
- 散列和加密
- 邮件
- 邮件内容
- 邮件发送
- 分页
- 模板解析器
- 动态解析器语法
- 队列消息
- 请求与输入
- 响应
- 视图
- 路由器
- 配置
- 验证操作
- 处理错误消息
- 错误消息与视图
- 可用的验证规则
- 有条件的验证规则
- 验证数组
- 错误消息
- 自定义验证规则
- 模型操作
- 定义模型与其属性
- 检索模型
- 插入与更新
- 删除模型
- 查询范围
- 事件操作
- 关联操作
- 定义关系
- 关系类型
- 多肽关系
- 关系查询
- 渴望加载
- 插入模型
- 数据库操作
- 基本用法
- 数据表结构
- 查询连贯操作
- 结果检索
- select子句
- 插入更新
- where子句
- 排序,分组,限制和偏移
- 文件附件
- Collection操作
- 属性操作
- 系列化json
- 数据库属性
- 数据库行为
- 控制器
- 后台控制器定义
- 后台页面
- 后台组件
- 后台表单
- 表单组件
- 表单视图
- 表单行为
- 后台列表
- 列表行为
- 列表过滤器
- 可用列类型
- 关系行为
- 关系行为类型
- 扩展关系行为
- 列表排序操作
- 导入导出操作
- 用于与权限
- corlate模板修改
- 修改顶部导航
- laravel问题
- 控制器不存在
- 控制器
- 路由组
- laravel笔记
- laravel 安装
- 伪静态配置
- 依赖注入 & 控制器
- 中间件
- 路由文件
- 视图