$collection = collect([1, 2, 2, 3, 4, 4, 4]);
dd($collection->all());
PS:$collection->dd()方法可以以 dd()模式输出,还有 dump()模式;
//返回平均值
$collection = collect([1, 2, 3, 4]);
return $collection->avg();
//返回分组平均值
$collection = collect([['男'=>1], ['女'=>1], ['男'=>3]]);
return $collection->avg('男');
return $collection->count();
PS:相关的还有 sum()、min()、max()等统计;
//值出现的次数
$collection = collect([1, 2, 2, 3, 4, 4, 4]);
return $collection->countBy();
//回调搜索相同指定片段的值的次数
$collection = collect(['[email protected]', '[email protected]', '[email protected]']);
return $collection->countBy(function ($value) {
return substr(strrchr($value, '@'), 1);
});
PS:相关的还有 groupBy()、keyBy()方法;
//diff 返回两个集合中不相同的
$collection = collect([1, 2, 3, 4, 5]);
return $collection->diff([3, 5]);
PS:其中还有 diffAssoc()、diffKeys()派生方法;
$collection = collect([1, 2, 2, 3, 4, 5, 5, 6]);
return $collection->duplicates();
//严格派生方法:
duplicatesStrict()
//返回判断成立的第一条数值
$collection = collect([1, 2, 3, 4]);
return $collection->first(function ($value) {
return $value > 2;
});
PS:相关的还有 every()、except()、only()、firstWhere()、last()等方法;
$collection = collect(['name'=>'Mr.Lee', 'details'=>['gender'=>'男', 'age'=>100]]);
return $collection->flatten();
$collection = collect(['name'=>'Mr.Lee', 'gender'=>'男']);
return $collection->get('name');
PS:相关的还有 pluck()等;
return $collection->has('name');
$collection = collect([1, 2, 3, 4, 5]);
//$collection->pop();
return $collection;
PS:相关的还有 pull()、push()、put()方法;
$collection = collect([1, 2, 3, 4, 5]);
return $collection->slice(3);
PS:相关的还有 splice()等方法;
$collection = collect([3, 1 , 5, 2, 7]);
return $collection->sort()->values();
//需要配合 values()方法
PS:相关的有 sortBy()、sortByDesc()、sortKeys()等;
$collection = collect([ ['name'=>'Mr.Lee', 'gender'=>'男'], ['name'=>'Miss.Zhang', 'gender'=>'女'] ]);
return $collection->where('name', 'Mr.Lee');