Laravel 集合常用方法的使用

什么是集合?即:它是一种更具读取性和处理能力的数组封装;比如,我们从数据库得到的数据列表,它就是一种集合;

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();
 
 
常用方法
1. all()方法,转换为属性形式输出,使用 dd 方法看类型;
2. avg()方法返回平均值;
//返回平均值
$collection = collect([1, 2, 3, 4]); 
return $collection->avg(); 

//返回分组平均值
$collection = collect([['男'=>1], ['女'=>1], ['男'=>3]]); 
return $collection->avg('男');
3. count()方法返回集合总数;
4. countBy()方法返回数值出现的次数或回调函数指定值出现的次数;
//值出现的次数
$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}
5. diff()方法返回集合数组之间不相同的部分,组合新的集合;
6. duplicates()返回重复的值;
7. first()返回成立后的第一个值;
8. flatten()将多维数组转换为一维;
9. get()通过键名找值;
10. has()判断集合中是否存在指定键;
11. pop()移出集合中最后一个值;
12. slice()返回指定值后续的集合;
13. sort()返回指定值后续的集合;
14. where()系列方法,和数据库条件一样;
$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

posted @ 2021-05-06 00:09  不睡  阅读(472)  评论(0编辑  收藏  举报