PHP构建二维汇总表格问题:班级-月度金额统计表列中月份重复的错误排查
Hey there! Let's fix that duplicate month issue in your table. I spotted a couple of mix-ups in your code that are causing the problem—let's break them down step by step.
1. Mixed-Up Array Logic for Months (Root of Duplicates)
Your $tblClasse array was intended to track unique months for table columns, but the logic was completely inverted:
if (!in_array($row['classe'],$tblClasse)) { $tblClasse[] = $row['mois']; }
This code checks if a class exists in the array, then adds the month to it. That means every time a new class appears in your data, you're adding its corresponding month again—even if that month was already in the array. No wonder you're getting duplicates!
2. Swapped Keys in the Row Loop
When looping through your main $tableau array, you used $mois=>$value, but $tableau is structured as $tableau[classe][mois] = sum_ec. The key here is actually the class, not the month—this was also messing up your row headers.
Fixed Full Code
Here's the corrected version with explanations:
<?php $tableau = array(); $uniqueMonths = array(); // Track unique months for table columns $rt = mysqli_query($db, $req_sit); while ($row = $rt->fetch_assoc()){ // Keep your main data structure (this part was correct!) $tableau[$row['classe']][$row['mois']] = $row['sum_ec']; // Collect unique months to avoid duplicate columns if (!in_array($row['mois'], $uniqueMonths)) { $uniqueMonths[] = $row['mois']; } } echo '<table border="1"> <tr> <th>Classe</th>'; // Clear label for the first column // Print month headers (no duplicates now!) foreach ($uniqueMonths as $mois) { echo '<th>' . htmlspecialchars($mois) . '</th>'; } echo '</tr>'; // Print each class's row of data foreach ($tableau as $classe => $monthValues) { echo '<tr>'; // Print the class name as the first cell echo '<td>' . htmlspecialchars($classe) . '</td>'; // Print each month's value for this class (or empty if no data) foreach ($uniqueMonths as $mois) { $display = isset($monthValues[$mois]) ? $monthValues[$mois] : " "; echo '<td>' . htmlspecialchars($display) . '</td>'; } echo '</tr>'; } ?>
Key Improvements:
- Replaced
$tblClassewith$uniqueMonthsto properly track distinct months (no more duplicate columns) - Corrected the row loop to use
$classeas the key, fixing row header labels - Added
htmlspecialchars()to all dynamic output to prevent XSS vulnerabilities (a critical best practice!) - Made header labels clearer for better readability
This should generate a clean table where each row represents a class, each column represents a unique month, and all totals are displayed correctly.
内容的提问来源于stack exchange,提问作者robot

