讨论:使用 Laravel 集合对数据进行分组统计的方式

有更好的写法欢迎指出:kissing_heart:

计算订单总金额#

$collection = collect([
    ['user_id' => 1, 'amount' => 100],
    ['user_id' => 1, 'amount' => 100],
]);

$collection->sum('amount');

// 200

计算每个用户的订单总金额#

// 用来存储计算结果
$data = [];

$collection = collect([
    ['user_id' => 1, 'amount' => 100],
    ['user_id' => 1, 'amount' => 100],
    ['user_id' => 2, 'amount' => 100],
    ['user_id' => 3, 'amount' => 100],
    ['user_id' => 5, 'amount' => 100],
]);

// 先根据用户进行分组
$groups = $collection->groupBy('user_id');
// 再统计每个用户的订单总金额
$groups->each(function($item, $key) use(&$data) {
    // 分组后的 $key 就是用户 ID
    $data[] = ['user_id' => $key, 'total_amount' => $item->sum('amount')];
});

// array (
//   0 =>
//   array (
//     'user_id' => 1,
//     'total_amount' => 200,
//   ),
//   1 =>
//   array (
//     'user_id' => 2,
//     'total_amount' => 100,
//   ),
//   2 =>
//   array (
//     'user_id' => 3,
//     'total_amount' => 100,
//   ),
//   3 =>
//   array (
//     'user_id' => 5,
//     'total_amount' => 100,
//   ),
// )

计算每个用户不同支付方式的订单总金额#

$data = [];
$collection = collect([
    ['user_id' => 1, 'amount' => 100, 'pay_type' => '微信'],
    ['user_id' => 1, 'amount' => 100, 'pay_type' => '微信'],
    ['user_id' => 1, 'amount' => 100, 'pay_type' => '支付宝'],
    ['user_id' => 2, 'amount' => 100, 'pay_type' => '微信'],
]);

$userGroups = $collection->groupBy('user_id');
$userGroups->each(function($userGroup, $user_id) use(&$data) {
    // 再根据支付方式分组
    $userPayTypeGroups = $userGroup->groupBy('pay_type');
    $userPayTypeGroups->each(function($userPayTypeGroup, $pay_type) use(&$data, $user_id){
        $data[] = ['user_id' => $user_id, 'pay_type' => $pay_type, 'total_amount' => $userPayTypeGroup->sum('amount')];
    });
});

// array (
//   0 => 
//   array (
//     'user_id' => 1,
//     'pay_type' => '微信',
//     'total_amount' => 200,
//   ),
//   1 => 
//   array (
//     'user_id' => 1,
//     'pay_type' => '支付宝',
//     'total_amount' => 100,
//   ),
//   2 => 
//   array (
//     'user_id' => 2,
//     'pay_type' => '微信',
//     'total_amount' => 100,
//   ),
// )
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。