如何为表格<tr>添加类实现月度及季度分组视觉分隔?
实现方案
一、优化SQL查询
首先要获取年份+月份的组合(避免跨年同月份混淆),同时把查询结果转成数组,方便后续判断下一条数据的归属:
<?php $query = ' SELECT Project_ID, Creation_date, DATE_FORMAT(Creation_date, "%Y-%m") AS Creation_year_month, -- 年月组合,区分跨年同月 DATE_FORMAT(Creation_date, "%m") AS Creation_date_M, DATE_FORMAT(Creation_date, "%Y") AS Creation_date_Y, Project_name FROM Projects ORDER BY Creation_date DESC '; $result = $conn->query($query); // 将结果转为数组,方便遍历判断下一条数据 $projects = []; while ($row = $result->fetch_assoc()) { $projects[] = $row; } $total = count($projects); ?>
二、PHP遍历添加类名
遍历数组时,跟踪上一条数据的年月和季度,判断当前行是否为当月最后一条、是否为季度末,然后添加对应类名:
<table> <thead> <tr> <th>创建日期</th> <th>项目名称</th> </tr> </thead> <tbody> <?php $prev_year_month = ''; $prev_quarter = ''; foreach ($projects as $index => $row): $current_year_month = $row['Creation_year_month']; $current_month = (int)$row['Creation_date_M']; $current_year = (int)$row['Creation_date_Y']; // 计算当前季度:1-3月为Q1,4-6为Q2,以此类推 $current_quarter = $current_year . '-Q' . ceil($current_month / 3); $class = []; // 判断是否为当月最后一条:下一条年月和当前不同,或是最后一条数据 if ($index === $total - 1 || $projects[$index + 1]['Creation_year_month'] !== $current_year_month) { $class[] = 'last'; } // 判断是否为季度最后一条:下一条季度和当前不同,或是最后一条数据 if ($index === $total - 1 || $projects[$index + 1]['Creation_date_Y'] . '-Q' . ceil((int)$projects[$index + 1]['Creation_date_M'] / 3) !== $current_quarter) { $class[] = 'quarter-end'; } $class_str = !empty($class) ? ' class="' . implode(' ', $class) . '"' : ''; ?> <tr<?= $class_str ?>> <td><?= $row['Creation_date']; ?></td> <td><?= $row['Project_name']; ?></td> </tr> <?php $prev_year_month = $current_year_month; $prev_quarter = $current_quarter; endforeach; ?> </tbody> </table>
三、CSS样式设置
表格行(tr)默认是table-row布局,margin不生效,推荐用border-bottom或padding-bottom实现间隔,也可以调整布局后用margin:
/* 基础行间距 */ tr { border-bottom: 1px solid #eee; } /* 每月最后一行和下月的间隔 */ tr.last { border-bottom: 10px solid transparent; } /* 每季度最后一行的更大间隔 */ tr.quarter-end { border-bottom: 20px solid transparent; } /* 若调整布局为block,可直接用margin */ /* tr { display: block; margin-bottom: 5px; } tr.last { margin-bottom: 15px; } tr.quarter-end { margin-bottom: 30px; } */
关键逻辑说明
- 用
年份+月份组合判断分组,避免跨年的同月份被误判为一组 - 通过数组遍历对比当前行与下一行的年月/季度,确定是否为组的最后一条
- 给不同组的最后一行添加类名,用CSS实现差异化间隔
内容的提问来源于stack exchange,提问作者Tony Chheng
相关产品推荐
相关产品推荐

