我的个人博客:逐步前行STEP
1、first
返回集合第一个通过指定测试的元素:
collect([1, 2, 3, 4])->first();
// 1
collect([1, 2, 3, 4])->first(function ($value, $key) {
return $value > 2;
});
// 3
2、last
返回集合中,最后一个通过指定测试的元素:
collect([1, 2, 3, 4])->last(function ($value, $key) {
return $value < 3;
});
// 2
collect([1, 2, 3, 4])->last();
// 4
3、keyBy
以指定键的值作为集合项目的键。如果几个数据项有相同的键,那在新集合中只显示最后一项:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'desk'],
['product_id' => 'prod-200', 'name' => 'chair'],
]);
$keyed = $collection->keyBy('product_id');
$keyed->all();
/*
[
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
$keyed = $collection->keyBy(function ($item) {
return strtoupper($item['product_id']);
});
$keyed->all();
/*
[
'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
4、map
遍历整个集合并将每一个数值传入回调函数。回调函数可以任意修改并返回项目,形成修改过的项目组成的新集合
$collection = collect([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]
5、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',
]
*/
6、merge
合并数组进集合。数组「键」对应的数值会覆盖集合「键」对应的数值:
$collection = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'price' => 200, 'discount' => false]
7、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']
8、pluck
获取集合中指定「键」所有对应的值
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
9、reduce
reduce 方法将集合缩减到单个数值,该方法会将每次迭代的结果传入到下一次迭代
$collection = collect([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
10、search
search 方法在集合内搜索指定的数值并返回找到的键。假如找不到项目,则返回 false
$collection = collect([2, 4, 6, 8]);
$collection->search(4);
// 1
$collection->search(function ($item, $key) {
return $item > 5;
});
// 2