讨论:使用 Laravel 集合对数据进行分组统计的方式
有更好的写法欢迎指出
计算订单总金额#
$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,
// ),
// )
推荐文章: