0

0

你知道Laravel Collection的实际使用场景有哪些吗?

藏色散人

藏色散人

发布时间:2021-08-26 15:26:51

|

2373人浏览过

|

来源于segmentfault

转载

下面由laravel教程栏目给大家介绍laravel collection的实际使用场景,希望对需要的朋友有所帮助!

这篇笔记用来整理Collection 在Laravel 的实际应用场景。

求和

需求:遍历$orders 数组,求price 的和。
      1,
    'user_id'       =>      1,
    'number'        =>      '13908080808',
    'status'        =>      0,
    'fee'           =>      10,
    'discount'      =>      44,
    'order_products'=> [
        ['order_id'=>1,'product_id'=>1,'param'=>'6寸','price'=>555.00,'product'=>['id'=>1,'name'=>'蛋糕名称','images'=>[]]],
        ['order_id'=>1,'product_id'=>1,'param'=>'7寸','price'=>333.00,'product'=>['id'=>1,'name'=>'蛋糕名称','images'=>[]]],
    ],
]];
1.使用传统的foreach 方式进行遍历:
$sum = 0;
foreach ($orders as $order) {
    foreach ($order['order_products'] as $item) {
        $sum += $item['price'];
    }
}
echo $sum;
2.使用集合的map、flatten、sum:
$sum = collect($orders)->map(function($order){
    return $order['order_products'];
})->flatten(1)->map(function($order){
    return $order['price'];
})->sum();

echo $sum;

map:遍历集合,返回一个新的集合。
flatten:将多维数组转换为一维。
sum:返回数组的和。

3.使用集合的flatMap、pluck、sum:
$sum = collect($orders)->flatMap(function($order){
    return $order['order_products'];
})->pluck('price')->sum();
echo $sum;

flatMap:和map 类似,不过区别在于flatMap 可以直接使用返回的新集合。

4.使用集合的flatMap、sum:
$sum = collect($orders)->flatMap(function($order){
    return $order['order_products'];
})->sum('price');

sum:可以接收一个列名作为参数进行求和。

格式化数据

需求:将如下结构的数组,格式化成下面的新数组。
// 带格式化数组
$gates = [
    'BaiYun_A_A17',
    'BeiJing_J7',
    'ShuangLiu_K203',
    'HongQiao_A157',
    'A2',
    'BaiYun_B_B230'
];

// 新数组
$boards = [
    'A17',
    'J7',
    'K203',
    'A157',
    'A2',
    'B230'
];
1.使用foreach 进行遍历:
$res = [];
foreach($gates as $key => $gate) {
    if(strpos($gate, '_') === false) {
        $res[$key] = $gate;
    }else{
        $offset = strrpos($gate, '_') + 1;
        $res[$key] = mb_substr($gate , $offset);
    }
}
var_dump($res);
2.使用集合的map以及php 的explode、end:
$res = collect($gates)->map(function($gate) {
    $parts = explode('_', $gate);
    return end($parts);
});
3.使用集合的map、explode、last、toArray:
$res = collect($gates)->map(function($gate) {
    return collect(explode('_', $gate))->last();
})->toArray();

explode:将字符串进行分割成数组
last:获取最后一个元素

统计GitHub Event

首先,通过此链接获取到个人事件json。

奇布塔
奇布塔

基于AI生成技术的一站式有声绘本创作平台

下载

一个 PushEvent计 5 分,一个 CreateEvent 计 4 分,一个 IssueCommentEvent计 3 分,一个 IssueCommentEvent 计 2 分,除此之外的其它类型的事件计 1 分,计算当前用户的时间得分总和。

$opts = [
        'http' => [
                'method' => 'GET',
                'header' => [
                        'User-Agent: PHP'
                ]
        ]
];
$context = stream_context_create($opts);
$events = json_decode(file_get_contents('http://api.github.com/users/0xAiKang/events', false, $context), true);
1.传统foreach 方式:
$eventTypes = []; // 事件类型
$score = 0; // 总得分
foreach ($events as $event) {
    $eventTypes[] = $event['type'];
}

foreach($eventTypes as $eventType) {
    switch ($eventType) {
        case 'PushEvent':
        $score += 5;
        break;
        case 'CreateEvent':
        $score += 4;
        break;
        case 'IssueEvent':
        $score += 3;
        break;
        case 'IssueCommentEvent':
        $score += 2;
        break;
        default:
        $score += 1;
        break;
    }
}
2.使用集合的map、pluck、sum 方法:
$score = $events->pluck('type')->map(function($eventType) {
   switch ($eventType) {
      case 'PushEvent':
      return 5;
      case 'CreateEvent':
      return 4;
      case 'IssueEvent':
      return 3;
      case 'IssueCommentEvent':
      return 2;
      default:
      return 1;
  }
})->sum();

使用集合的链式编程,可以很好地解决上面那种多次遍历的问题。

3.使用集合中的map、pluck、get 方法:
$score = $events->pluck('type')->map(function($eventType) {
   return collect([
       'PushEvent'=> 5,
       'CreateEvent'=> 4,
       'IssueEvent'=> 3,
       'IssueCommentEvent'=> 2
   ])->get($eventType, 1); // 如果不存在则默认等于1
})->sum();
4.尝试将该需求,封装成一个类:
class GithubScore {
    private $events;

    private function __construct($events){
        $this->events = $events;
    }

    public static function score($events) {
        return (new static($events))->scoreEvents();
    }

    private function scoreEvents() {
        return $this->events->pluck('type')->map(function($eventType){
            return $this->lookupEventScore($eventType, 1);
        })->sum();
    }

    public function lookupEventScore($eventType, $default_value) {
       return collect([
           'PushEvent'=> 5,
           'CreateEvent'=> 4,
           'IssueEvent'=> 3,
           'IssueCommentEvent'=> 2
       ])->get($eventType, $default_value); // 如果不存在则默认等于1
    }
}

var_dump(GithubScore::score($events));

格式化数据

需求:将以下数据格式化成新的结构。
$messages = [
    'Should be working now for all Providers.',
    'If you see one where spaces are in the title let me know.',
    'But there should not have blank in the key of config or .env file.'
];

// 格式化之后的结果
- Should be working now for all Providers. \n
- If you see one where spaces are in the title let me know. \n
- But there should not have blank in the key of config or .env file.
1.传统的foreach 方式:
$comment = '- ' . array_shift($messages);
foreach ($messages as $message) {
    $comment .= "\n -  ${message}";
}
var_dump($comment);
2.使用集合的map、implode方法:
$comment = collect($messages)->map(function($message){
    return '- ' . $message;
})->implode("\n");
var_dump($comment);

多个数组求差

需求:两组数据分别代表去年的营收和今年的营收,求每个月的盈亏情况。
$lastYear = [
    6345.75,
    9839.45,
    7134.60,
    9479.50,
    9928.0,
    8652.00,
    7658.40,
    10245.40,
    7889.40,
    3892.40,
    3638.40,
    2339.40
];

$thisYear = [
    6145.75,
    6895.00,
    3434.00,
    9349350,
    9478.60,
    7652.80,
    4758.40,
    10945.40,
    3689.40,
    8992.40,
    7588.40,
    2239.40
];
1.传统的foreach 方式:
$profit = [];
foreach($thisYear as $key => $monthly){
    $profit[$key] = $monthly - $lastYear[$key];
}
var_dump($profit);
2.使用集合的zip、first、last:
$profit = collect($thisYear)->zip($lastYear)->map(function($monthly){
    return $monthly->first() - $monthly->last();
});

zip:将给定数组的值与相应索引处的原集合的值合并在一起。

创建lookup 数组

需求:将如下数组格式化成下面的结果:
$employees = [
    [
        'name' => 'example',
        'email' => 'example@exmaple.com',
        'company' => 'example Inc.'
    ],
    [
        'name' => 'Lucy',
        'email' => 'lucy@example.com',
        'company' => 'ibm Inc.'
    ],
    [
        'name' => 'Taylor',
        'email' => 'toylor@laravel.com',
        'company'=>'Laravel Inc.'
    ]
];

// 格式化之后的结果
$lookup = [
    'example' => 'example@example.com',
    'Lucy' => ‘lucy@example.com’,
    'Taylor'=> 'toylor@laravel.com'
];
1.传统的foreach 方式:
$emails = [];
foreach ($employees as $key => $value) {
    $emails[$value['name']] = $value['email'];
}
2.使用集合的reduce 方法:
$emails = collect($employees)->reduce(function($emailLookup, $employee){
    $emailLookup[$employee['name']] = $employee['email'];
    return $emailLookup;
},[]);

reduce:将每次迭代的结果传递给下一次迭代直到集合减少为单个值。

3.使用集合的pluck 方法:
$emails = collect($employees)->pluck('name', 'email');

相关推荐:最新的五个Laravel视频教程

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
laravel组件介绍
laravel组件介绍

laravel 提供了丰富的组件,包括身份验证、模板引擎、缓存、命令行工具、数据库交互、对象关系映射器、事件处理、文件操作、电子邮件发送、队列管理和数据验证。想了解更多laravel的相关内容,可以阅读本专题下面的文章。

319

2024.04.09

laravel中间件介绍
laravel中间件介绍

laravel 中间件分为五种类型:全局、路由、组、终止和自定。想了解更多laravel中间件的相关内容,可以阅读本专题下面的文章。

278

2024.04.09

laravel使用的设计模式有哪些
laravel使用的设计模式有哪些

laravel使用的设计模式有:1、单例模式;2、工厂方法模式;3、建造者模式;4、适配器模式;5、装饰器模式;6、策略模式;7、观察者模式。想了解更多laravel的相关内容,可以阅读本专题下面的文章。

372

2024.04.09

thinkphp和laravel哪个简单
thinkphp和laravel哪个简单

对于初学者来说,laravel 的入门门槛较低,更易上手,原因包括:1. 更简单的安装和配置;2. 丰富的文档和社区支持;3. 简洁易懂的语法和 api;4. 平缓的学习曲线。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

374

2024.04.10

laravel入门教程
laravel入门教程

本专题整合了laravel入门教程,想了解更多详细内容,请阅读专题下面的文章。

85

2025.08.05

laravel实战教程
laravel实战教程

本专题整合了laravel实战教程,阅读专题下面的文章了解更多详细内容。

65

2025.08.05

laravel面试题
laravel面试题

本专题整合了laravel面试题相关内容,阅读专题下面的文章了解更多详细内容。

68

2025.08.05

json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

418

2023.08.07

php中文乱码如何解决
php中文乱码如何解决

本文整理了php中文乱码如何解决及解决方法,阅读节专题下面的文章了解更多详细内容。

1

2026.01.28

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PHP课程
PHP课程

共137课时 | 9.8万人学习

JavaScript ES5基础线上课程教学
JavaScript ES5基础线上课程教学

共6课时 | 11.2万人学习

PHP新手语法线上课程教学
PHP新手语法线上课程教学

共13课时 | 0.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号