您的位置:首页 > 编程语言 > PHP开发

二十三、PHP框架Laravel学习笔记——集合的常用方法

2021-05-14 17:31 896 查看

一.常用方法

  1. all()方法,转换为属性形式输出,使用 dd 方法看类型;
$collection = collect([1, 2, 2, 3, 4, 4, 4]);
dd($collection->all());

PS:$collection->dd()方法可以以 dd()模式输出,还有 dump()模式;

  1. avg()方法返回平均值;
//返回平均值
$collection = collect([1, 2, 3, 4]);
return $collection->avg();

//返回分组平均值
$collection = collect([['男'=>1], ['女'=>1], ['男'=>3]]);
return $collection->avg('男');

  1. count()方法返回集合总数;
return $collection->count();

PS:相关的还有 sum()、min()、max()等统计;

  1. countBy()方法返回数值出现的次数或回调函数指定值出现的次数;
//值出现的次数
$collection = collect([1, 2, 2, 3, 4, 4, 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()方法;

  1. diff()方法返回集合数组之间不相同的部分,组合新的集合;
//diff 返回两个集合中不相同的
$collection = collect([1, 2, 3, 4, 5]);
return $collection->diff([3, 5]);

PS:其中还有 diffAssoc()、diffKeys()派生方法;

  1. duplicates()返回重复的值;
$collection = collect([1, 2, 2, 3, 4, 5, 5, 6]);
return $collection->duplicates();

//严格派生方法:
duplicatesStrict()

  1. first()返回成立后的第一个值;
//返回判断成立的第一条数值
$collection = collect([1, 2, 3, 4]);
return $collection->first(function ($value) {
return $value > 2;
});

PS:相关的还有 every()、except()、only()、firstWhere()、last()等方法;

  1. flatten()将多维数组转换为一维;
$collection = collect(['name'=>'Mr.Lee', 'details'=>['gender'=>'男', 'age'=>100]]);
return $collection->flatten();


  1. get()通过键名找值;
$collection = collect(['name'=>'Mr.Lee', 'gender'=>'男']);
return $collection->get('name');

PS:相关的还有 pluck()等;

  1. has()判断集合中是否存在指定键;
return $collection->has('name');

  1. pop()移出集合中最后一个值;
$collection = collect([1, 2, 3, 4, 5]);

//$collection->pop();
return $collection;

PS:相关的还有 pull()、push()、put()方法;

  1. slice()返回指定值后续的集合;
$collection = collect([1, 2, 3, 4, 5]);
return $collection->slice(3);

PS:相关的还有 splice()等方法;

  1. sort()返回指定值后续的集合;
$collection = collect([3, 1 , 5, 2, 7]);
return $collection->sort()->values();


//需要配合 values()方法
PS:相关的有 sortBy()、sortByDesc()、sortKeys()等;

  1. where()系列方法,和数据库条件一样;
$collection = collect([ ['name'=>'Mr.Lee', 'gender'=>'男'], ['name'=>'Miss.Zhang', 'gender'=>'女'] ]);
return $collection->where('name', 'Mr.Lee');

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: