- 常用方法
- all()方法,转换为属性形式输出,使用dd方法看类型
$collection = collect([‘Mr.Zhang’, ‘李四’, ‘王五’, null]);
dd($collection->all());
PS:$collection->dd()方法可以以dd()模式输出,还有dump()模式
b. avg()方法返回平均值:
//返回平均值
$collection = collect([1, 2, 2, 3, 4]);
return $collection->avg();
//返回分组平均值
$collection = collect([[‘男’=>1], [‘女’=>1], [‘男’=>3]]);
return $collection->avg();
c. count()方法返回集合总数:
return $collection->count();
Ps:相关的还有sum()、min()、max()等统计
d. countBy()方法返回数值出现的次数或回调函数指定值出现的次数
//值出现的次数
$collection = collect([1, 2, 2, 3, 4]);
return $collection->countBy();
//回调搜索相同指定片段的值的次数
$collection = collect([‘xiaoxin@163.com’, ‘yihu@163.com’, ‘xiaoying@qq.com’]);
return $collection->countBy(function ($value){
return substr(strrchr($value, ‘@’), 1);
});
Ps: 相关的还有groupBy()、keyBy()方法;
e. diff()方法返回集合数组之间不相同的部分,组合新的集合
//diff返回两个集合中不相同的
$collection = collect([1,2,3,4,5]);
return $collection->diff([3, 5]);//返回值1,2,4
Ps: 其中还有diffAssoc()、diffKeys()派生方法;
f. duplicates()返回重复的值;
//返回判断成立的第一条数值
$collection = collect([1,2,2,3,4,5,5,6]);
return $collection->duplicates(); //严格派生方法:duplicatesStrict()
g. first()返回成立后的第一个值
//返回判断成立的第一条数值
$collection = collect([1,2,3,4]);
return $collection->first(function ($value){
return $value > 2;
});
PS:相关的还有every()、except()、only()、firstWhere()、last()等方法
h. flatten()将多维数组转换为一维
$collection = collect([‘name’=>’Mr.lee’, ‘details’=>[‘gender’=>’男’, ‘age’=>100]]);
return $collection->flatten();
i. get()通过键名找值:
$collection = collect([‘name’=>’Mr.Lee’, ‘gender’=>’男’]);
return $collection->get(‘name’);
Ps:相关的还有pluck()等
j. has()判断集合中是否存在指定键;
$collection = collect([‘name’=>’Mr.Lee’, ‘gender’=>’男’]);
return $collection->has(‘name’);
k. pop()移出集合中最后一个值:
$collection = collect([1,2,3,4,5]);
$collection->pop();//如果只是return这一行代码,只会返回最后一个值5
return $collection;//这一行return返回的是数组里1,2,3,4 因为5已经被pop移出了
PS:相关的还有pull()、push()、put()方法;
l. slice()返回指定值后续的集合:(包括那个指定的值)
$collection = collect([‘xiaoxin@163.com’, ‘yihu@163.com’, ‘xiaoying@qq.com’]);
return $collection->slice(1);
Ps: 相关的有sortBy()、sortByDesc()、sortKeys()等
m. sort()返回指定值后续的集合:(返回值会将其排序)
$collection = collect([3,1,5,2,7]);
return $collection->sort()->values(); //需要配合values()方法
PS: 相关的有sortDesc()、sortBy()、sortByDesc()、sortKeys()等
n. where()系列方法,和数据库条件一样