PHP如何将同用户同日期的多条位置记录合并在表格列中展示
PHP 相同用户同日期位置记录合并表格实现方案
现有原始数据
你目前的用户位置数组如下:
$arr = [ [ 'user_id' => 5, 'l_id' => 10, 'Name' => 'John Doe', 'Location' => 'Chicago', 'date' => '2021-10-02' ], [ 'user_id' => 5, 'l_id' => 11, 'Name' => 'John Doe', 'Location' => 'Houston', 'date' => '2021-10-02' ], [ 'user_id' => 6, 'l_id' => 12, 'Name' => 'Rob Doe', 'Location' => 'Dallas', 'date' => '2021-10-02' ], [ 'user_id' => 6, 'l_id' => 13, 'Name' => 'Rob Doe', 'Location' => 'Philadelphia', 'date' => '2021-10-02' ], ];
原有问题
你当前的遍历逻辑会重复输出相同用户、相同日期的姓名和日期字段,无法实现合并展示的效果。
修改后实现代码
方案1:遍历过程中判断上一条记录(无需预处理数组)
$html = ''; // 记录上一条的用户+日期唯一标识 $lastUniqueKey = ''; foreach ($arr as $index => $ar) { // 用user_id+date作为唯一判断键,保证同用户同日期的记录合并 $currentUniqueKey = $ar['user_id'] . '_' . $ar['date']; // 如果不是第一条记录,且用户变更,加分隔线 if ($index !== 0 && $currentUniqueKey !== $lastUniqueKey) { $html .= '<tr><td colspan="3"><hr></td></tr>'; } // 判断当前是否是同用户同日期的第一条记录 if ($currentUniqueKey === $lastUniqueKey) { // 不是第一条,姓名和日期列留空 $nameCell = ''; $dateCell = ''; } else { // 是第一条,输出姓名和日期 $nameCell = htmlspecialchars($ar['Name']); $dateCell = htmlspecialchars($ar['date']); // 更新标识 $lastUniqueKey = $currentUniqueKey; } $html .= '<tr> <td>' . $nameCell . '</td> <td>' . $dateCell . '</td> <td>' . htmlspecialchars($ar['Location']) . '</td> </tr>'; }
注:新增htmlspecialchars处理是为了避免XSS安全问题,没有特殊需求可去掉
方案2:先按规则分组再渲染(逻辑更清晰,可扩展性更高)
// 第一步:先按用户+日期分组 $grouped = []; foreach ($arr as $ar) { $key = $ar['user_id'] . '_' . $ar['date']; if (!isset($grouped[$key])) { $grouped[$key] = [ 'Name' => $ar['Name'], 'date' => $ar['date'], 'locations' => [] ]; } $grouped[$key]['locations'][] = $ar['Location']; } // 第二步:渲染HTML $html = ''; foreach ($grouped as $index => $item) { // 不同组之间加分隔线 if ($index !== 0) { $html .= '<tr><td colspan="3"><hr></td></tr>'; } foreach ($item['locations'] as $locIndex => $location) { $nameCell = $locIndex === 0 ? htmlspecialchars($item['Name']) : ''; $dateCell = $locIndex === 0 ? htmlspecialchars($item['date']) : ''; $html .= '<tr> <td>' . $nameCell . '</td> <td>' . $dateCell . '</td> <td>' . htmlspecialchars($location) . '</td> </tr>'; } }
配套HTML结构无需修改
还是用你原来的结构即可:
<table> <thead> <tr> <th>Name</th> <th>Date</th> <th>Location</th> </tr> </thead> <tbody> <?= $html; ?> </tbody> </table>
如果需要更美观的合并效果,也可以给第一行的姓名、日期单元格加rowspan属性,值为当前用户的位置数量,展示效果会更符合传统合并单元格的样式。
内容的提问来源于stack exchange,提问作者glitchy
相关产品推荐
相关产品推荐

