Illuminate\Support\Collection
类提供了一个更具可读性和更便于处理数组数据的封装。
$collection = collect([‘张三‘, ‘李四‘, ‘王五‘, null]); //以底层数组形式输出 return $collection->all(); //map 方法,类似访问器,可修改输出 return $collection->map(function ($value, $key) { return $key.‘[‘.$value.‘]‘; }); //支持链式,reject 移出非 true 的值 return $collection->reject(function ($value, $key) { return $value === null; })->map(function ($value, $key) { return $key.‘[‘.$value.‘]‘; }); //filter 筛选为 true 的值,和 reject 相反 return $collection->filter(function ($value, $key) { return $value === null; }); //search 找到后返回 key,找不到返回 false return $collection->search(‘王五‘); //集合的分割 return $collection->chunk(2); //迭代输出 $collection->each(function ($item, $key) { echo $item; });
$collection = collect([‘Mr.Zhang‘, ‘李四‘, ‘王五‘, null]); Collection::macro(‘toUpper‘, function () { return $this->map(function ($value) { return strtoupper($value); }); }); return $collection->toUpper();
//返回平均值 $collection = collect([1, 2, 3, 4]); return $collection->avg(); //返回分组平均值 $collection = collect([[‘男‘=>1], [‘女‘=>1], [‘男‘=>3]]); return $collection->avg(‘男‘);
//值出现的次数 $collection = collect([1, 2, 2, 3, 4, 4, 4]); return $collection->countBy();//{"1":1,"2":2,"3":1,"4":3} //回调搜索相同指定片段的值的次数 $collection = collect([‘xiaoxin@163.com‘, ‘yihu@163.com‘, ‘xiaoying@qq.com‘]); return $collection->countBy(function ($value) { return substr(strrchr($value, ‘@‘), 1); });//{"163.com":2,"qq.com":1}
$collection = collect([ [‘name‘=>‘Mr.Lee‘, ‘gender‘=>‘男‘], [‘name‘=>‘Miss.Zhang‘, ‘gender‘=>‘女‘] ]); return $collection->where(‘name‘, ‘Mr.Lee‘);//[{"name":"Mr.Lee","gender":"\u7537"}]
官方链接:https://learnku.com/docs/laravel/8.x/collections/9390
原文:https://www.cnblogs.com/bushui/p/14733494.html