laravel中提供了强大的集合,集合可以帮助我们做很多的事情、减少功能编码,但是必须熟悉,知道才可以
https://learnku.com/docs/laravel/6.x/collections/5161
创建集合
collect([1,2,3]);
判断数组是否存在指定的键
$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
$collection->has('product');
// true
$collection->has(['product', 'amount']);
// true
$collection->has(['amount', 'price']);
// falsecollapse()
collapse 方法将多个数组的集合合并成一个数组的集合:
$collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
$collapsed = $collection->collapse();
$collapsed->all();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
combine()
combine 方法可以将一个集合的值作为键,再将另一个数组或集合的值作为值合并成一个集合:
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]
collect()
collect 方法返回一个新的 Collection 实例,其中包含当前集合中的项目:
$collectionA = collect([1, 2, 3]);
$collectionB = $collectionA->collect();
$collectionB->all();
// [1, 2, 3]
count()
all()
countBy()方法计算集合中每个值的出现次数
countBy 方法计算集合中每个值的出现次数。默认情况下,该方法计算每个元素的出现次数:
$collection = collect([1, 2, 2, 2, 3]);
$counted = $collection->countBy();
$counted->all();
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'],
]
*/
dd()
用于打印集合元素并中断脚本执行,如果不想中断,可以使用 dump 方法代替
diff()
diff 方法将集合与其它集合或者 PHP 数组 进行值的比较。然后返回原集合中存在而指定集合中不存在的值:
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]
diffAssoc() 方法与另外一个集合或基于它的键和值的 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]
diffKeys()
diffKeys 方法和另外一个集合或 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]
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']
duplicatesStrict()
此方法与 duplicates 方法具有相同的签名;但是,所有值都以「严格」的方式进行比较
except()
except 方法返回集合中除了指定键之外的所有集合项:
$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);
$filtered = $collection->except(['price', 'discount']);
$filtered->all();
// ['product_id' => 1]
与 except 对应的是 only 方法。
filter()
filter 方法使用给定的回调函数过滤集合,只保留那些通过指定条件测试的集合项:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
$filtered->all();
firstWhere() 返回第一个符合条件的数据
$collection->firstWhere('age', '>=', 18);
get()
get 方法返回指定键的集合项,如果该键在集合中不存在,则返回 null:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('name');
// taylor
你可以任选一个默认值作为第二个参数传递:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('foo', 'default-value');
// default-value
groupBy()
intersect()
intersect 方法从原集合中移除在指定数组 或集合中不存在的任何值。生成的集合将会保留原集合的键:
$collection = collect(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']
intersectByKeys()
intersectByKeys 方法从原集合中移除在指定 数组 或集合中不存在的任何键:
$collection = collect([
'serial' => 'UX301', 'type' => 'screen', 'year' => 2009
]);
$intersect = $collection->intersectByKeys([
'reference' => 'UX404', 'type' => 'tab', 'year' => 2011
]);
$intersect->all();
// ['type' => 'screen', 'year' => 2009]
keyBy()
keys() 返回数组中索引键名集合
https://learnku.com/docs/laravel/6.x/collections/5161
flatten()
flatten 方法将多维集合转为一维集合:
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);$flattened = $collection->flatten();$flattened->all();// ['taylor', 'php', 'javascript'];
你可以选择性地传入「深度」参数:
$collection = collect([
'Apple' => [
['name' => 'iPhone 6S', 'brand' => 'Apple'],
],
'Samsung' => [
['name' => 'Galaxy S7', 'brand' => 'Samsung']
],]);$products = $collection->flatten(1);$products->values()->all();/*
[
['name' => 'iPhone 6S', 'brand' => 'Apple'],
['name' => 'Galaxy S7', 'brand' => 'Samsung'],
]
*/
在这个例子里,调用 flatten 时不传入深度参数的话也会将嵌套数组转成一维的,然后返回 ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']。传入深度参数能让你限制设置返回数组的层数。
flip()
flip 方法将集合的键和对应的值进行互换:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);$flipped = $collection->flip();$flipped->all();// ['taylor' => 'name', 'laravel' => 'framework']
forget()
forget 方法将通过指定的键来移除集合中对应的内容:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);$collection->forget('name');$collection->all();<?php
//$data = [
// 'identityType' => 'sometimes|in:1,2',
// 'identityNum' => 'sometimes',
// 'name' => 'james'
//];
$data = array(
[
'name' => "shawn",
"email" => "shawn@qq.com",
"company" => "QQ"
],
[
'name' => "nicole",
"email" => "nicole@360.com",
"company" => "360"
],
[
'name' => "test",
"email" => "test@baidu.com",
"company" => "baidu"
]
);
$collect = collect($data);
P($collect->all());
P($collect->first());
P($collect->last());
$lookup = $collect->pluck("email", "name")->toarray();
P($lookup); //pluck 和array_column 是一样的
P(array_column($data, 'email', 'name'));
P($collect->where('name', '=', 'james')->all());
P('contains');
P($collect->contains('name', 'test'));
P('数组中的长度是 count:' . $collect->count());
P('数组中的长度是:' . $collect->count());
P($collect->implode('name', ' , '));<?php
//P(Carbon::now()->isToday());
/**
*
*
* reject()
* reject方法使用给定回调过滤集合,该回调应该为所有它想要从结果集合中移除的数据项返回true:
*
* $collection = collect([1, 2, 3, 4]);
*
* $filtered = $collection->reject(function ($item) {
* return $item > 2;
* });
*
* $filtered->all();
* // [1, 2]
* 和reduce方法相对的方法是filter方法。
*
* reverse()
* reverse方法将集合数据项的顺序颠倒:
*
* $collection = collect([1, 2, 3, 4, 5]);
* $reversed = $collection->reverse();
* $reversed->all();
* // [5, 4, 3, 2, 1]
* search()
* search方法为给定值查询集合,如果找到的话返回对应的键,如果没找到,则返回false:
*
* $collection = collect([2, 4, 6, 8]);
* $collection->search(4);
* // 1
*
* intersect()
* intersect方法返回两个集合的交集:
*
* $collection = collect(['Desk', 'Sofa', 'Chair']);
* $intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
* $intersect->all();
* // [0 => 'Desk', 2 => 'Chair']
* 正如你所看到的,结果集合只保持原来集合的键。
*
* isEmpty()
* 如果集合为空的话isEmpty方法返回true;否则返回false:
*
* collect([])->isEmpty();
*
* each()
* each方法迭代集合中的数据项并传递每个数据项到给定回调:
*
* $collection = $collection->each(function ($item, $key) {
* //
* });
* 回调返回false将会终止循环:
*
* $collection = $collection->each(function ($item, $key) {
*
* return false;
* });
*
*flip()
* flip方法将集合的键值做交换:
*
* $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
* $flipped = $collection->flip();
* $flipped->all();
* // ['taylor' => 'name', 'laravel' => 'framework']
* forget()
* forget方法通过键从集合中移除数据项:
*
* $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
* $collection->forget('name');
* $collection->all();
* // [framework' => 'laravel']
* 注意:不同于大多数的集合方法,forget不返回新的修改过的集合;它只修改所调用的集合。
*
* forPage()
* forPage方法返回新的包含给定页数数据项的集合:
*
* $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9])->forPage(2, 3);
*
* $collection->all();
* // [4, 5, 6]
* 该方法需要传入页数和每页显示数目参数。
*
* get()
* get方法返回给定键的数据项,如果不存在,返回null:
*
* $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
* $value = $collection->get('name');
* // taylor
*
*
*
* diff()
* diff方法将集合和另一个集合或原生PHP数组作比较:
*
* $collection = collect([1, 2, 3, 4, 5]);
* $diff = $collection->diff([2, 4, 6, 8]);
* $diff->all();
* // [1, 3, 5]
*
* 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
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*当处理栅栏系统如Bootstrap时该方法在视图中尤其有用,建设你有一个想要显示在栅栏中的Eloquent模型集合:
*
* @foreach ($products->chunk(3) as $chunk)
* <div class="row">
* @foreach ($chunk as $product)
* <div class="col-xs-4">{{ $product->name }}</div>
* @endforeach
* </div>
* @endforeach
*
*
*
* chunk()
* chunk方法将一个集合分割成多个小尺寸的小集合:
*
* $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' => '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'],
* ]
*
*
*/