序言
集合是一个很好用的数据类型,在 PHP 中我们常常使用数组来处理数据,而laravel提供了许多集合封装好的方法来处理数据,许多数组做不到或者处理比较繁琐的,集合却可以轻易做到,可以让我们少些一些处理数据的方法。
使用方法:
- collect() 创建集合
辅助函数 collect 为给定数组返回一个新的 Illuminate\Support\Collection 实例
$collection = collect([
[
'user_id' => '1',
'title' => 'Helpers in Laravel',
'content' => 'Create custom helpers in Laravel',
'category' => 'php'
],
[
'user_id' => '2',
'title' => 'Testing in Laravel',
'content' => 'Testing File Uploads in Laravel',
'category' => 'php'
]
]);
- search() 给定的值查找集合
如果这个值在集合中,会返回对应的键。如果没有数据项匹配对应的值,会返回 false
$names = collect(['Alex', 'John', 'Jason', 'Martyn', 'Hanlin']);
$result = $names->search('Jason');
// 2
- chunk() 分块
chunk 方法将集合分割为多个给定大小的较小集合。将集合显示到网格中非常有用.
flatten() 将多维集合转为一维集合
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['taylor', 'php', 'javascript'];
4.where() 查询
where 方法,可以像数据库查询方法where()一样通过给定键值对过滤集合:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$result = $collection->where('price', 100)->all();
/*
[
1 =>['product' => 'Chair', 'price' => 100],
3 =>['product' => 'Door', 'price' => 100],
]
*/
- dump() 打印集合
dump 打印集合的方法。 它可用于在任何位置的调试和查找集合内的内容
$collection->whereIn('price', [100, 150])
->dump()
->where('product', 'Door');
- map() 遍历集合
map 方法用于遍历整个集合。 它接受回调作为参数。 value 和 key 被传递给回调。 回调可以修改值并返回它们。 最后,返回修改项的新集合实例
$changed = $collection->map(function ($value, $key) {
$value['user_id'] += 1;
return $value;
});
$result = $changed->all();
- max() 最大值
$result = $collection->max('price');
//200
- pluck() 获取某列值
$result = $collection->pluck('product')->all();
//["Desk","Chair","Bookcase","Door"];
- contains()
contains 方法只检查集合是否包含给定值。 只传递一个参数时才会出现这种情况
$contains = collect(['country' => 'USA', 'state' => 'NY']);
$contains->contains('USA');
// true
$contains->contains('UK');
// false
- forget()
forget 从集合中删除该项。 传递一个键,它就会从集合中删除该项目。
$forget = collect(['country' => 'usa', 'state' => 'ny']);
$forget->forget('country')->all();
/*
[
"state" => "ny"
]
*/
- zip()
zip 方法在与集合的值对应的索引处合并给定数组的值:
$collection = collect(['Chair', 'Desk']);
$result = $collection->zip([100, 200])->all();
// [['Chair', 100], ['Desk', 200]]
- combine()
combine 方法可以将一个集合的键和另一个数组或集合的值连接起来:
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]
- diff()
diff 方法将集合和另一个集合或原生PHP数组以基于值的方式作比较,这个方法会返回存在于原来集合而不存在于给定集合的值
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]
- diffAssoc()
diffAssoc 方法会基于键值将一个集合和另一个集合或原生 PHP 数组进行比较。该方法返回只存在于第一个集合中的键值对:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6
]);
$diff = $collection->diffAssoc([
'color' => 'yellow',
'type' => 'fruit',
'remain' => 3,
'used' => 6
]);
$result = $diff->all();
// ['color' => 'orange', 'remain' => 6]
- first()、 last()
first 方法返回集合的第一个元素:
$result = collect([1, 2, 3, 4])->first();
// 1
$result = collect([1, 2, 3, 4])->first(function ($value, $key) {
return $value > 2;
});
// 3
$result = collect([1, 2, 3, 4])->last();
// 4
- flatten()
flatten 方法将多维度的集合变成一维的:
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['taylor', 'php', 'javascript'];
- flip()
flip 方法将集合的键值做交换:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$flipped = $collection->flip();
$flipped->all();
// ['taylor' => 'name', 'laravel' => 'framework']
- forPage()
forPage 方法返回新的包含给定页数数据项的集合。该方法接收页码数作为第一个参数,每页显示数据项数作为第二个参数
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);
$chunk->all();
// [4, 5, 6]
- groupBy()
groupBy 方法通过给定键分组集合数据项
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->toArray();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
- keyBy()
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'],
]
*/
- sort()、sortBy() 、sortByDesc() 排序
sort 方法对集合进行排序, 排序后的集合保持原来的数组键
sortBy() 方法通过给定键对集合进行排序(升序), 排序后的集合保持原有数组索引,在本例中,使用 values 方法重置键为连续索引。
sortByDesc() 则为降序
$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]
$collection = collect([
['name' => 'Desk', 'price' => 200],
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
]);
$sorted = $collection->sortBy('price');
$sorted->values()->all();
/*
[
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
['name' => 'Desk', 'price' => 200],
]
*/
可以用回调来判断如何排序集合的值:
$collection = collect([
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$sorted = $collection->sortBy(function ($product, $key) {
return count($product['colors']);
});
$sorted->values()->all();
/*
[
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]
*/
- take()
take 方法使用指定数目的数据项返回一个新的集合:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]
- only(),except() (只对一维数据有效果)
only返回集合中指定键的所有项目:(except 则返回集合中除了指定键的所有项目)
$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
$filtered = $collection->only(['product_id', 'name']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']
$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
$filtered = $collection->except(['price', 'discount']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']
//二维数据处理例子:
$list = collect($list)->sortByDesc('value')->keyBy('name')->map(function($item){
//return collect($item)->only('id');
return collect($item)->except('id');
});
-
shift(),
-
put()
prepend在集合前面增加一个项目, put在集合尾巴添加:
$collection = collect(['one' => 1, 'two', => 2]);
$collection->prepend(0, 'zero');
$collection->all();
// ['zero' => 0, 'one' => 1, 'two', => 2]
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->put('price', 100);
$collection->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
- each(), map(), transform()
each()遍历集合中的项目,并将之传入回调函数:
回调函数返回 false 以中断循环:
$collection = $collection->each(function ($item, $key) {
if (/* some condition */) {
return false;
}
});
map()遍历整个集合并将每一个数值传入回调函数。回调函数可以任意修改并返回项目,形成修改过的项目组成的新集合:
$collection = collect([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]
transform()遍历集合并对集合内每一个项目调用指定的回调函数。集合的项目将会被回调函数返回的数值取代掉:
$collection = collect([1, 2, 3, 4, 5]);
$collection->transform(function ($item, $key) {
return $item * 2;
});
$collection->all();
// [2, 4, 6, 8, 10]
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->all();
/*
[
'Sales' => ['John Doe', 'Jane Doe'],
'Marketing' => ['Johnny Doe'],
]
*/
laravel 集合用法中文文档: https://laravelacademy.org/post/19507