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
转换
并集
去重
严格去重
除非
除非为空
除非不为空
解包
值
当...时
当为空时
当不为空时
条件
严格条件
介于之间
包含于
严格包含于
实例类型为
不介于之间
不包含于
严格不包含于
不为Null
为Null
包装
拉链
所有()该 all 方法简单地返回由集合表示的底层数组:
$collection = new Collection([1, 2, 3]);
$collection->all();
// [1, 2, 3]平均()avg 方法的别名。
平均()该 avg 方法返回给定键的 平均值:
$average = new Collection([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
// 20
$average = new Collection([1, 1, 2, 4])->avg();
// 2块()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 方法将给定的 array 或集合值追加到集合的末尾:
$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;
});
// false该 contains 方法在检查项值时使用“宽松”比较,这意味着一个具有整数值的字符串将被视为与相同值的整数相等。使用 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()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 方法基于其键名,将集合与另一个集合或一个普通的 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()该 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']严格重复项()此方法具有与 重复项 方法相同的签名; 然而, 所有值都使用“严格的”比较。
遍历()该 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']您可以选择传递 offset 作为第二个参数:
$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]For the inverse of filter, see the reject method.
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](#method-where) 方法,您可以向 firstWhere 方法传递一个参数。在此场景下,firstWhere 方法将返回第一个项目,该项目的给定键的值为“truthy”:
$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 方法会交换集合的键和其对应的值:
$collection = new Collection(['name' => 'peter', 'platform' => 'october']);
$flipped = $collection->flip();
$flipped->all();
// ['peter' => 'name', 'october' => 'platform']遗忘()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 方法返回给定键处的项。如果键不存在,则返回 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()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'],
],
]
*/有()该 has 方法用于判断给定键是否存在于集合中:
$collection = new Collection(['account_id' => 1, 'product' => 'Desk']);
$collection->has('email');
// falseimplode()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();
// falsejoin()该 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();
// 4map()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 方法遍历集合中的项,并将每个嵌套项的值传递给指定的回调。回调可以自由地修改项并返回它,从而形成一个由修改后的项组成的新集合:
$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]映射到组()The 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 方法会遍历集合,并将每个值传递给给定的回调。该回调应返回一个包含单个键值对的关联数组:
$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 方法返回给定键的最大值:
$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 方法返回集合中具有指定键的项:
$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的逆操作,请参见except方法。
填充()该 pad 方法将用给定值填充数组,直到数组达到指定大小。此方法类似于 array_pad PHP 函数。
若要向左填充,应指定负数大小。如果给定大小的绝对值小于或等于数组的长度,则不会进行任何填充:
$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()该 pipe 方法将集合传递给给定的回调并返回结果:
$collection = new Collection([1, 2, 3]);
$piped = $collection->pipe(function ($collection) {
return $collection->sum();
});
// 6提取()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()put 方法在集合中设置给定的键和值:
$collection = new Collection(['product_id' => 1, 'name' => 'Desk']);
$collection->put('price', 100);
$collection->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]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)归约()该 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()该 sort 方法对集合进行排序:
$collection = new Collection([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]排序后的集合保留原始数组键。在此示例中,我们使用了 值 方法来重置键为连续编号的索引。
对于对嵌套数组或对象的集合进行排序,请参阅 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']],
]
*/sortByDesc()这个方法具有与 sortBy 方法相同的签名,但会对集合进行相反的排序。
排序键()sortKeys 方法会根据其底层关联数组的键对集合进行排序:
$collection = new Collection([
'id' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeys();
$sorted->all();
/*
[
'first' => 'John',
'id' => 22345,
'last' => 'Doe',
]
*/降序排序键()此方法与 sortKeys 方法具有相同的签名,但会以相反的顺序对集合进行排序。
剪接()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 方法将一个集合分割成给定数量的组:
$collection = new Collection([1, 2, 3, 4, 5]);
$groups = $collection->split(3);
$groups->toArray();
// [[1, 2], [3, 4], [5]]求和()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']);
});
// 6take()该 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 方法将集合转换为一个普通的 PHP array。如果集合的值是 数据库模型,这些模型也将被转换为数组:
$collection = new Collection(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/注意:
toArray也会将其所有嵌套对象转换为数组。如果您想按原样获取底层数组,请改用all方法。
toJson()toJson 方法将集合转换为 JSON:
$collection = new Collection(['name' => 'Desk', 'price' => 200]);
$collection->toJson();
// '{"name":"Desk","price":200}'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方法。
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()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'],
]
*/严格条件()此方法具有与[where](#method-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()该 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 方法具有相同的签名; 但是,所有值都使用“严格”比较进行比较。
筛选为实例()该 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 方法根据给定的键/值过滤集合,该键/值不包含在给定数组中:
$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 方法会过滤给定键不为 null 的项:
$collection = new Collection([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
]);
$filtered = $collection->whereNotNull('name');
$filtered->all();
/*
[
['name' => 'Desk'],
['name' => 'Bookcase'],
]
*/为空()该 whereNull 方法过滤给定键为 null 的项:
$collection = new Collection([
['name' => 'Desk'],
['name' => null],
['name' => 'Bookcase'],
]);
$filtered = $collection->whereNull('name');
$filtered->all();
/*
[
['name' => null],
]
*/包裹()静态 wrap 方法在适用时将给定值封装到集合中:
$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()该 zip 方法将给定数组的值与原始集合中相应索引处的值合并:
$collection = new Collection(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]