这个 October\Rain\Support\Collection 类提供了一个流畅, 便捷的包装器, 用于处理数据数组. 例如, 请看以下代码. 我们将从数组中创建一个新的集合实例, 对每个元素运行 strtoupper 函数, 然后移除所有空元素.
$collection = new October\Rain\Support\Collection(['stewie', 'brian', null]);
$collection = $collection
->map(function ($name) {
return strtoupper($name);
})
->reject(function ($name) {
return empty($name);
})
;Collection 类允许你链式调用其方法,以对底层数组执行流畅的映射和归约。通常情况下,每个 Collection 方法都会返回一个全新的 Collection 实例。
如上所述,将数组传递给 October\Rain\Support\Collection 类的构造函数将为给定数组返回一个新实例。因此,创建集合就像这样简单:
$collection = new October\Rain\Support\Collection([1, 2, 3]);默认情况下,数据库模型的集合始终以 Collection 实例的形式返回;但是,你可以在应用程序中方便的任何地方使用 Collection 类.
在本文档的其余部分中,我们将讨论 Collection 类上可用的每个方法。请记住,所有这些方法都可以被链式调用,以流畅地操作底层数组。此外,几乎每个方法都返回一个新的 Collection 实例,允许你在必要时保留集合的原始副本。
您可以从此表中选择任意方法来查看其用法示例:
所有
平均
平均
分块
展平
合并
连接
包含
严格包含
计数
按计数
交叉连接
dd
差集
关联差集
键差集
转储
重复项
严格重复项
遍历
过滤
第一个
第一个符合条件
展平映射
展平
翻转
移除
分页
获取
按分组
存在
内爆
交集
按键交集
是否为空
是否非空
连接
按键分组
键
最后一个
映射
映射到
扩展映射
映射到分组
带键映射
最大值
中位数
合并
递归合并
最小值
众数
第N个
只保留
填充
分区
管道
提取
弹出
前置
拉取
推入
放置
随机
归约
拒绝
替换
递归替换
反转
搜索
移出首项
洗牌
跳过
切片
部分
排序
按...排序
按...倒序排序
键排序
键倒序排序
拼接
分割
求和
获取
轻触
执行次数
转换为数组
转换为JSON
转换
并集
去重
严格去重
除非
除非为空
除非非空
解包
值
当...时
当为空时
当非空时
条件
严格条件
介于之间
在...中
严格在...中
实例类型是
不介于之间
不在...中
严格不在...中
非空
为空
包裹
压缩
所有()all 方法仅仅返回该集合所表示的底层数组:
$collection = new Collection([1, 2, 3]);
$collection->all();
// [1, 2, 3]平均()avg 方法的别名。
avg()该 avg 方法返回给定键的 平均值:
$average = new Collection([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
// 20
$average = new Collection([1, 1, 2, 4])->avg();
// 2chunk()该 chunk 方法将集合拆分为多个指定大小的较小集合:
$collection = new Collection([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]这种方法在CMS页面中特别有用,尤其是在使用网格系统时,例如Bootstrap。想象一下,你有一组想要在网格中显示的模型:
{% for chunk in products.chunk(3) %}
<div class="row">
{% for product in chunk %}
<div class="col-4">{{ product.name }}</div>
{% endfor %}
</div>
{% endfor %}折叠()该 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]组合()combine 方法将集合的值作为键,与另一个数组或集合的值结合。
$collection = new Collection(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]concat()该 concat 方法将给定的 数组 或集合值追加到集合的末尾:
$collection = new Collection(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
$concatenated->all();
// ['John Doe', 'Jane Doe', 'Johnny Doe']包含()该 contains 方法确定集合是否包含给定项:
$collection = new Collection(['name' => 'Desk', 'price' => 100]);
$collection->contains('Desk');
// true
$collection->contains('New York');
// false您还可以向 contains 方法传递一个键 / 值对,这将确定给定对是否存在于集合中:
$collection = new Collection([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->contains('product', 'Bookcase');
// false最后,您还可以给 contains 方法传递一个回调,以执行您自己的真值测试:
$collection = new Collection([1, 2, 3, 4, 5]);
$collection->contains(function ($value, $key) {
return $value > 5;
});
// falsecontains 方法在检查项值时使用“宽松”比较,这意味着一个具有整数值的字符串将被视为与相同值的整数相等。使用 containsStrict 方法进行“严格”比较过滤。
严格包含()此方法与 contains 方法具有相同的签名;但是,所有值都使用“严格”比较进行比较。
计数()该 count 方法返回集合中的项目总数:
$collection = new Collection([1, 2, 3, 4]);
$collection->count();
// 4countBy()此 countBy 方法统计集合中值的出现次数。 默认情况下,该方法会统计每个元素的出现次数:
$collection = new Collection([1, 2, 2, 2, 3]);
$counted = $collection->countBy();
$counted->all();
// [1 => 1, 2 => 3, 3 => 1]但是,您可以向 countBy 方法传递一个回调,以根据自定义值计算所有项:
$collection = new Collection(['alice@gmail.tld', 'bob@yahoo.tld', 'carlos@gmail.tld']);
$counted = $collection->countBy(function ($email) {
return substr(strrchr($email, "@"), 1);
});
$counted->all();
// ['gmail.tld' => 2, 'yahoo.tld' => 1]交叉连接()crossJoin 方法在给定数组或集合之间对集合的值执行交叉连接,返回一个包含所有可能排列组合的笛卡尔积:
$collection = new Collection([1, 2]);
$matrix = $collection->crossJoin(['a', 'b']);
$matrix->all();
/*
[
[1, 'a'],
[1, 'b'],
[2, 'a'],
[2, 'b'],
]
*/
$collection = new Collection([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()dd 方法会转储集合项,并终止脚本执行:
$collection = new Collection(['John Doe', 'Jane Doe']);
$collection->dd();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/如果你不想停止执行脚本, 请使用 dump 方法代替.
diff()该 diff 方法比较该集合与另一个集合或一个普通的 PHP array:
$collection = new Collection([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]diffAssoc()diffAssoc 方法基于其键和值,将集合与另一个集合或一个普通的 PHP array 进行比较。此方法将返回原始集合中,但在给定集合中不存在的键值对:
$collection = new Collection([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6
]);
$diff = $collection->diffAssoc([
'color' => 'yellow',
'type' => 'fruit',
'remain' => 3,
'used' => 6,
]);
$diff->all();
// ['color' => 'orange', 'remain' => 6]diffKeys()diffKeys 方法会根据其键将集合与另一个集合或纯 PHP array 进行比较。此方法将返回原始集合中不存在于给定集合中的键/值对:
$collection = new Collection([
'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 = new Collection(['John Doe', 'Jane Doe']);
$collection->dump();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/如果您想在转储集合后停止执行脚本,请改用 dd 方法。
重复项()该 duplicates 方法从集合中检索并返回重复值:
$collection = new Collection(['a', 'b', 'a', 'c', 'b']);
$collection->duplicates();
// [2 => 'a', 4 => 'b']如果集合包含数组或对象,你可以传入希望检查重复值的属性的键:
$employees = new Collection([
['email' => 'samantha@example.tld', 'position' => 'Developer'],
['email' => 'john@example.tld', 'position' => 'Designer'],
['email' => 'elaine@example.tld', 'position' => 'Developer'],
])
$employees->duplicates('position');
// [2 => 'Developer']严格重复项()此方法与 duplicates 方法具有相同的签名;但是,所有值都使用 "严格的" 比较进行比较。
遍历()each 方法遍历集合中的项,并将每个项传递给回调:
$collection->each(function ($item, $key) {
//
});如果您想停止遍历项目,您可以从回调中返回false:
$collection->each(function ($item, $key) {
if (/* some condition */) {
return false;
}
});每个()every 方法创建一个新集合,包含每第 n 个元素:
$collection = new Collection(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->every(4);
// ['a', 'e']您也可以选择将偏移量作为第二个参数传入:
$collection->every(4, 1);
// ['b', 'f']过滤()该 filter 方法通过给定回调过滤集合,只保留那些通过指定真值测试的项:
$collection = new Collection([1, 2, 3, 4]);
$filtered = $collection->filter(function ($item) {
return $item > 2;
});
$filtered->all();
// [3, 4]对于 filter 的逆操作, 请参阅 reject 方法.
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首个符合条件()firstWhere 方法返回集合中具有给定键/值对的第一个元素:
$collection = new Collection([
['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 方法,你可以向 firstWhere 方法传递一个参数。在这种情况下,firstWhere 方法将返回给定项目键的值为“真值”的第一个项目:
$collection->firstWhere('age');
// ['name' => 'Linda', 'age' => 14]flatMap()flatMap 方法遍历集合,并将每个值传递给指定的回调。回调可以自由地修改并返回该项,从而形成一个新的修改后的项集合。然后,数组被展平一层:
$collection = new Collection([
['name' => 'Sally'],
['school' => 'Harvard'],
['age' => 28]
]);
$flattened = $collection->flatMap(function ($values) {
return array_map('strtoupper', $values);
});
$flattened->all();
// ['name' => 'SALLY', 'school' => 'HARVARD', 'age' => '28'];展平()该 flatten 方法将一个多维集合展平为一个单一维度:
$collection = new Collection(['name' => 'peter', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['peter', 'php', 'javascript'];flip()该 flip 方法交换集合的键和其对应的值:
$collection = new Collection(['name' => 'peter', 'platform' => 'october']);
$flipped = $collection->flip();
$flipped->all();
// ['peter' => 'name', 'october' => 'platform']forget()forget 方法通过其键从集合中移除一个项:
$collection = new Collection(['name' => 'peter', 'platform' => 'october']);
$collection->forget('name');
$collection->all();
// ['platform' => 'october']注意: 与大多数其他集合方法不同,
forget不会返回一个新的修改后的集合;它会修改被调用的集合。
forPage()该 forPage 方法返回一个新集合,其中包含将存在于给定页码上的项:
$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9])->forPage(2, 3);
$collection->all();
// [4, 5, 6]该方法分别需要页码和每页显示的条目数。
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-valuegroupBy 方法根据给定的键对集合中的项目进行分组:
$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'],
],
]
*/拥有()has 方法用于判断集合中是否存在给定键:
$collection = new Collection(['account_id' => 1, 'product' => 'Desk']);
$collection->has('email');
// false连接()implode 方法将集合中的项连接起来。其参数取决于集合中项的类型。
如果集合包含数组或对象,你应该传入你希望连接的属性的键,以及你希望放置在值之间的“连接”字符串:
$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'intersect 方法会移除任何不在给定 array 或集合中的值:
$collection = new Collection(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']如您所见,所得集合将保留原始集合的键。
按键求交集()该 intersectByKeys 方法会移除原始集合中所有不在给定 array 或集合中的键:
$collection = new Collection([
'serial' => 'UX301', 'type' => 'screen', 'year' => 2009
]);
$intersect = $collection->intersectByKeys([
'reference' => 'UX404', 'type' => 'tab', 'year' => 2011
]);
$intersect->all();
// ['type' => 'screen', 'year' => 2009]是否为空() isEmpty方法返回true如果集合为空;否则返回false:
new Collection([])->isEmpty();
// true非空()isNotEmpty 方法在集合不为空时返回 true;否则,返回 false:
new Collection([])->isNotEmpty();
// false连接()该 join 方法将集合的值用字符串连接起来:
new Collection(['a', 'b', 'c'])->join(', '); // 'a, b, c'
new Collection(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'
new Collection(['a', 'b'])->join(', ', ' and '); // 'a and b'
new Collection(['a'])->join(', ', ' and '); // 'a'
new Collection([])->join(', ', ' and '); // ''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'],
]
*/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']最后()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该 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方法。
mapInto()mapInto() 方法遍历集合,通过将值传入构造函数,创建一个给定类的新实例:
class Currency
{
/**
* Create a new currency instance.
*
* @param string $code
* @return void
*/
function __construct(string $code)
{
$this->code = $code;
}
}
$collection = new Collection(['AUD', 'USD', 'GBP']);
$currencies = $collection->mapInto(Currency::class);
$currencies->all();
// [Currency('AUD'), Currency('USD'), Currency('GBP')]mapSpread()mapSpread 方法迭代集合中的项目,并将每个嵌套的项目值传递给给定的回调函数。回调函数可以自由修改项目并返回它,从而形成一个由修改后的项目组成的新集合:
$collection = new Collection([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()该 mapToGroups 方法根据给定的回调将集合的项分组。该回调应返回一个包含单个键/值对的关联数组,从而形成一个新的分组值集合:
$collection = new Collection([
[
'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()mapWithKeys 方法遍历集合,并将每个值传递给指定的回调。该回调应返回一个关联数组,其中包含一个键值对:
$collection = new Collection([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john@example.tld'
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane@example.tld'
]
]);
$keyed = $collection->mapWithKeys(function ($item) {
return [$item['email'] => $item['name']];
});
$keyed->all();
/*
[
'john@example.tld' => 'John',
'jane@example.tld' => 'Jane',
]
*/max 方法返回给定键的最大值:
$max = new Collection([['foo' => 10], ['foo' => 20]])->max('foo');
// 20
$max = new Collection([1, 2, 3, 4, 5])->max();
// 5中位数()该 median 方法返回给定键的中位数:
$median = new Collection([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');
// 15
$median = new Collection([1, 1, 2, 4])->median();
// 1.5合并()merge 方法将给定数组或集合与原始集合合并。如果给定项中的字符串键与原始集合中的字符串键匹配,给定项的值将覆盖原始集合中的值:
$collection = new Collection(['product_id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'price' => 200, 'discount' => false]如果给定项的键是数字,它们的值将被追加到集合的末尾:
$collection = new Collection(['Desk', 'Chair']);
$merged = $collection->merge(['Bookcase', 'Door']);
$merged->all();
// ['Desk', 'Chair', 'Bookcase', 'Door']递归合并()该 mergeRecursive 方法将给定的数组或集合与原始集合递归合并。如果给定项中的字符串键与原始集合中的字符串键匹配,则这些键的值将合并到一个数组中,并且此过程是递归进行的:
$collection = new Collection(['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 = new Collection([['foo' => 10], ['foo' => 20]])->min('foo');
// 10
$min = new Collection([1, 2, 3, 4, 5])->min();
// 1mode()该 mode 方法返回给定键的 众数:
$mode = new Collection([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');
// [10]
$mode = new Collection([1, 1, 2, 4])->mode();
// [1]nth()该 nth 方法创建一个新集合,由每隔 n 个元素组成:
$collection = new Collection(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->nth(4);
// ['a', 'e']你可以选择传递一个偏移量作为第二个参数:
$collection->nth(4, 1);
// ['b', 'f']only()only方法会返回集合中带有指定键的项:
$collection = new Collection(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
$filtered = $collection->only(['product_id', 'name']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']对于 only 的逆操作,请参阅 [排除](#method-except) 方法。
填充()pad 方法将用给定值填充数组,直到数组达到指定大小。此方法的行为类似于 array_pad PHP 函数。
To pad to the left, you should specify a negative size. No padding will take place if the absolute value of the given size is less than or equal to the length of the array:
$collection = new Collection(['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']分区()该 partition 方法可以与 list PHP 函数结合使用,以分离通过给定真值测试的元素与未通过的元素:
$collection = new Collection([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 方法将集合传递给给定的回调并返回结果:
$collection = new Collection([1, 2, 3]);
$piped = $collection->pipe(function ($collection) {
return $collection->sum();
});
// 6pluck()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']pop()pop 方法从集合中移除并返回最后一个项:
$collection = new Collection([1, 2, 3, 4, 5]);
$collection->pop();
// 5
$collection->all();
// [1, 2, 3, 4]前置()该 prepend 方法向集合的开头添加一项:
$collection = new Collection([1, 2, 3, 4, 5]);
$collection->prepend(0);
$collection->all();
// [0, 1, 2, 3, 4, 5]拉取()该 pull 方法通过其键从集合中移除并返回一个项:
$collection = new Collection(['product_id' => 'prod-100', 'name' => 'Desk']);
$collection->pull('name');
// 'Desk'
$collection->all();
// ['product_id' => 'prod-100']推入()push 方法将一个项目追加到集合的末尾:
$collection = new Collection([1, 2, 3, 4]);
$collection->push(5);
$collection->all();
// [1, 2, 3, 4, 5]放置()put 方法在集合中设置给定的键和值:
$collection = new Collection(['product_id' => 1, 'name' => 'Desk']);
$collection->put('price', 100);
$collection->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]随机()该 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)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拒绝()reject 方法使用给定的回调过滤集合。该回调应返回 true,以移除任何它希望从结果集合中移除的项:
$collection = new Collection([1, 2, 3, 4]);
$filtered = $collection->reject(function ($item) {
return $item > 2;
});
$filtered->all();
// [1, 2]有关 reject 方法的逆操作, 请参阅 filter 方法。
替换()replace 方法的行为类似于 merge;然而,除了覆盖具有字符串键的匹配项之外,replace 方法还将覆盖集合中具有匹配数字键的项:
$collection = new Collection(['James', 'Scott', 'Dan']);
$replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']);
$replaced->all();
// ['James', 'Victoria', 'Dan', 'Finn']此方法类似于 replace,但它会递归处理数组,并将相同的替换过程应用于内部值:
$collection = new Collection(['George', 'Scott', ['James', 'Victoria', 'Finn']]);
$replaced = $collection->replaceRecursive(['Charlie', 2 => [1 => 'King']]);
$replaced->all();
// ['Charlie', 'Scott', ['James', 'King', 'Finn']]反转()该 reverse 方法反转集合项的顺序:
$collection = new Collection([1, 2, 3, 4, 5]);
$reversed = $collection->reverse();
$reversed->all();
// [5, 4, 3, 2, 1]搜索()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;
});
// 2shift()该 shift 方法移除并返回集合中的第一个元素:
$collection = new Collection([1, 2, 3, 4, 5]);
$collection->shift();
// 1
$collection->all();
// [2, 3, 4, 5]洗牌()shuffle 方法随机打乱集合中的项:
$collection = new Collection([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] (generated randomly)跳过()该 skip 方法返回一个新集合,不包含指定数量的开头项:
$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$collection = $collection->skip(4);
$collection->all();
// [5, 6, 7, 8, 9, 10]切片()该 slice 方法返回从给定索引开始的集合切片:
$collection = new Collection([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 方法来重新索引它们。
some()contains 方法的别名。
排序()该 sort 方法对集合进行排序:
$collection = new Collection([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]排序后的集合保留了原始数组的键。在这个例子中,我们使用了 values 方法来重置键为连续编号的索引。
对于嵌套数组或对象的集合排序,请参阅 sortBy 和 sortByDesc 方法。
如果你的排序需求更高级,你可以将回调传递给 sort 并使用你自己的算法。请参阅 PHP 关于 usort 的文档,集合的 sort 方法在底层调用的正是它。
按...排序()该 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 方法来将键重置为连续编号的索引。
你还可以传递你自己的回调来决定如何排序集合中的值:
$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']],
]
*/按降序排序()这个方法具有与 sortBy 方法相同的签名,但将以相反的顺序对集合进行排序。
排序键()该 sortKeys 方法依据其底层关联数组的键对集合进行排序:
$collection = new Collection([
'id' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeys();
$sorted->all();
/*
[
'first' => 'John',
'id' => 22345,
'last' => 'Doe',
]
*/按键降序排序()这个方法具有与 sortKeys 方法相同的签名,但将以相反的顺序对集合进行排序。
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]拼接()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]split()该 split 方法将集合拆分为指定数量的组:
$collection = new Collection([1, 2, 3, 4, 5]);
$groups = $collection->split(3);
$groups->toArray();
// [[1, 2], [3, 4], [5]]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获取()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]轻触()tap 方法将集合传递给给定的回调函数,允许你在特定点“介入”集合并对其中的项进行操作,同时不影响集合本身:
new Collection([2, 4, 3, 1, 5])
->sort()
->tap(function ($collection) {
Log::debug('Values after sorting', $collection->values()->toArray());
})
->shift();
// 1times()静态的 times 方法通过调用回调函数指定的次数来创建一个新的集合:
$collection = Collection::times(10, function ($number) {
return $number * 9;
});
$collection->all();
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]toArray()该 toArray 方法将集合转换为一个普通的 PHP array. 如果集合的值是 数据库模型, 这些模型也将被转换为数组:
$collection = new Collection(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/注意:
toArray还会将其所有嵌套对象转换为数组。如果您想按原样获取底层数组,请使用all方法代替。
转为Json()该 toJson 方法 转换 该 集合 为 JSON:
$collection = new Collection(['name' => 'Desk', 'price' => 200]);
$collection->toJson();
// '{"name":"Desk","price":200}'转换()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方法。
union()该 union 方法将给定的数组添加到集合中。如果给定的数组包含已存在于原始集合中的键,则原始集合中的值将被优先保留:
$collection = new Collection([1 => ['a'], 2 => ['b']]);
$union = $collection->union([3 => ['c'], 1 => ['b']]);
$union->all();
// [1 => ['a'], 2 => ['b'], 3 => ['c']]唯一()unique 方法返回集合中所有唯一项。返回的集合保留原始数组键,因此在本例中我们将使用 values 方法将键重置为连续编号的索引:
$collection = new Collection([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]在处理嵌套数组或对象时,您可以指定用于确定唯一性的键:
$collection = new Collection([
['name' => 'iPhone 12', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'iPhone 13', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S21', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);
$unique = $collection->unique('brand');
$unique->values()->all();
/*
[
['name' => 'iPhone 13', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Galaxy S21', 'brand' => 'Samsung', 'type' => 'phone'],
]
*/您也可以传递您自己的回调来确定项目的唯一性:
$unique = $collection->unique(function ($item) {
return $item['brand'].$item['type'];
});
$unique->values()->all();
/*
[
['name' => 'iPhone 12', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S21', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]
*/unique 方法在检查项值时使用“宽松”比较, 这意味着一个带有整数值的字符串将被视为与具有相同值的整数相等. 使用 uniqueStrict 方法进行“严格”比较筛选.
uniqueStrict()此方法与 unique 方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。
该 unless 方法将执行给定的回调除非传递给该方法的第一个参数的求值结果为 true:
$collection = new Collection([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 方法。
除非为空()别名 用于 该 whenNotEmpty 方法。
除非不为空()whenEmpty 方法的别名。
解包()静态 unwrap 方法在适用时,从给定值中返回集合的基础项:
Collection::unwrap(new Collection('John Doe'));
// ['John Doe']
Collection::unwrap(['John Doe']);
// ['John Doe']
Collection::unwrap('John Doe');
// 'John Doe'值()该 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],
]
*/当()when 方法将会在传递给该方法的第一个参数评估结果为 true 时执行给定的回调:
$collection = new Collection([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 = new Collection(['michael', 'tom']);
$collection->whenEmpty(function ($collection) {
return $collection->push('steve');
});
$collection->all();
// ['michael', 'tom']
$collection = new Collection();
$collection->whenEmpty(function ($collection) {
return $collection->push('steve');
});
$collection->all();
// ['steve']
$collection = new Collection(['michael', 'tom']);
$collection->whenEmpty(function ($collection) {
return $collection->push('steve');
}, function ($collection) {
return $collection->push('prince');
});
$collection->all();
// ['michael', 'tom', 'prince']要了解 whenEmpty 的逆操作,请参阅 whenNotEmpty 方法。
该 whenNotEmpty 方法将在集合不为空时执行给定的回调:
$collection = new Collection(['michael', 'tom']);
$collection->whenNotEmpty(function ($collection) {
return $collection->push('steve');
});
$collection->all();
// ['michael', 'tom', 'steve']
$collection = new Collection();
$collection->whenNotEmpty(function ($collection) {
return $collection->push('steve');
});
$collection->all();
// []
$collection = new Collection();
$collection->whenNotEmpty(function ($collection) {
return $collection->push('steve');
}, function ($collection) {
return $collection->push('prince');
});
$collection->all();
// ['prince']要查找与此相反的 whenNotEmpty,请参阅 whenEmpty 方法。
条件()该 where 方法通过给定的键/值对过滤集合:
$collection = new Collection([
['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 = new Collection([
['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'],
]
*/whereStrict()此方法与 where 方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。
whereBetween()该 whereBetween 方法在给定范围内筛选集合:
$collection = new Collection([
['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 = new Collection([
['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 方法进行“严格”比较筛选。
严格地在其中()此方法具有与[whereIn](#method-wherein)方法相同的签名;但是,所有值都使用“严格”比较进行比较。
whereInstanceOf()whereInstanceOf 方法通过给定的类类型过滤集合:
use App\User;
use App\Post;
$collection = new Collection([
new User,
new User,
new Post,
]);
$filtered = $collection->whereInstanceOf(User::class);
$filtered->all();
// [App\User, App\User]不在...之间()whereNotBetween 方法在给定范围内筛选集合:
$collection = new Collection([
['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()该 whereNotIn 方法根据不包含在给定数组中的给定键/值来筛选集合:
$collection = new Collection([
['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 方法通过“严格”比较进行过滤。
严格不在其中()此方法与 whereNotIn 方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。
whereNotNull()The whereNotNull method filters items where the given key is not null:
$collection = new Collection([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
]);
$filtered = $collection->whereNotNull('name');
$filtered->all();
/*
[
['name' => 'Desk'],
['name' => 'Bookcase'],
]
*/whereNull()The whereNull method filters items where the given key is null:
$collection = new Collection([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
]);
$filtered = $collection->whereNull('name');
$filtered->all();
/*
[
['name' => null],
]
*/wrap()The static wrap method wraps the given value in a collection when applicable:
$collection = Collection::wrap('John Doe');
$collection->all();
// ['John Doe']
$collection = Collection::wrap(['John Doe']);
$collection->all();
// ['John Doe']
$collection = Collection::wrap(new Collection('John Doe'));
$collection->all();
// ['John Doe']zip()The zip method merges together the values of the given array with the values of the original collection at the corresponding index:
$collection = new Collection(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]