如何在PHP中实现分组值求和?附学生费用详情代码场景
实现PHP学生费用分组求和并展示详情表格
我来帮你完善这个学生费用详情的代码,实现按「Fees Group」分组求和的功能。核心思路是遍历费用数据时,跟踪当前分组的ID,当分组切换时输出上一组的合计,最后再处理最后一组的合计:
<table class="table table-hover"> <thead> <tr> <th>Fees Group</th> <th>Fees Type</th> <th>Fees Amount</th> <th>Action</th> </tr> </thead> <tbody> <?php // 初始化全局合计变量 $total_amount = 0; $total_deposite_amount = 0; $total_fine_amount = 0; $total_discount_amount = 0; $total_balance_amount = 0; // 分组合计相关变量 $group_total = 0; $current_group_id = null; // 假设$fee_details是你的费用数据数组,包含group_id, fees_group, fees_type, amount等字段 foreach ($fee_details as $fee) { // 当分组ID变化时,输出上一组的合计行 if ($current_group_id !== null && $current_group_id != $fee['group_id']) { ?> <tr class="table-info"> <td colspan="2"><strong>Group Total</strong></td> <td><strong><?php echo number_format($group_total, 2); ?></strong></td> <td></td> </tr> <?php // 重置当前分组合计 $group_total = 0; } // 更新当前分组ID $current_group_id = $fee['group_id']; // 累加当前分组的金额 $group_total += $fee['amount']; // 累加全局合计 $total_amount += $fee['amount']; // 输出单条费用记录 ?> <tr> <td><?php echo htmlspecialchars($fee['fees_group']); ?></td> <td><?php echo htmlspecialchars($fee['fees_type']); ?></td> <td><?php echo number_format($fee['amount'], 2); ?></td> <td> <!-- 这里放你的操作按钮,比如编辑/删除 --> <button class="btn btn-sm btn-primary">Edit</button> <button class="btn btn-sm btn-danger">Delete</button> </td> </tr> <?php } // 输出最后一组的合计行 if ($current_group_id !== null) { ?> <tr class="table-info"> <td colspan="2"><strong>Group Total</strong></td> <td><strong><?php echo number_format($group_total, 2); ?></strong></td> <td></td> </tr> <?php } // 输出全局总计行 ?> <tr class="table-success"> <td colspan="2"><strong>Grand Total</strong></td> <td><strong><?php echo number_format($total_amount, 2); ?></strong></td> <td></td> </tr> </tbody> </table>
关键逻辑说明:
- 分组跟踪:用
$current_group_id记录当前遍历的分组ID,每次循环先判断是否切换了分组 - 分组合计:切换分组时输出上一组的合计,并重置
$group_total;每次循环累加当前记录的金额到分组合计 - 安全输出:用
htmlspecialchars()避免XSS注入风险 - 格式美化:用
number_format()让金额显示更规范 - 最后分组处理:遍历结束后要单独输出最后一组的合计,避免遗漏
内容的提问来源于stack exchange,提问作者Maniraj Murugan
相关产品推荐
相关产品推荐

