讨论:使用 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,
//   ),
// )
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!