You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将表格中街道地址相同的记录合并显示在同一行?

问题翻译

我现有如下样式的表格:
原表格样式
为提升可读性,希望修改为如下样式:
目标表格样式

当前实现代码如下,请问如何修改以达成需求?

<?php

$sql = "SELECT
companyname,
ordernumber,
equipment,
theserial,
type,
theaddress
FROM table";

$result = mysqli_query($con, $sql);

?>


<table id="moreinfotable" name="moreinfotable" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>OrderNumber</th>
<th>Equipment</th>
<th>Serial</th>
<th>Type</th>
<th>Address</th>

</tr>
</thead>

<?php

while($row = mysqli_fetch_array($result)) { 

$companyname = $row['companyname'];
$ordernumber = $row['ordernumber'];
$equipment = $row['equipment'];
$theserial = $row['theserial'];
$type = $row['type'];
$theaddress = $row['theaddress'];

echo '<tr>';
echo '<td>' . $companyname . '</td>';
echo '<td>' . $ordernumber . '</td>';
echo '<td>' . $equipment . '</td>';
echo '<td>' . $theserial . '</td>';
echo '<td>' . $type . '</td>';
echo '<td>' . $theaddress . '</td>';
echo'</tr>';

} 

?>


</table>

解决方案

要实现同公司名称单元格合并的效果,核心是通过rowspan属性合并相同公司的行,同时确保同公司的记录连续排列,具体修改步骤如下:

  1. 修改SQL查询语句
    新增排序规则,确保同一公司的记录连续排列,这是合并单元格的基础:

    $sql = "SELECT
    companyname,
    ordernumber,
    equipment,
    theserial,
    type,
    theaddress
    FROM table
    ORDER BY companyname"; // 按公司名称排序,让同公司记录连在一起
    
  2. 重构PHP循环逻辑
    需要先统计每个公司的记录数,再在输出时动态设置rowspan,跳过重复的公司名称单元格:

    <?php
    // 先把所有查询结果存入数组
    $rows = [];
    while($row = mysqli_fetch_array($result)) {
        $rows[] = $row;
    }
    
    // 统计每个公司的记录数量
    $company_row_counts = [];
    foreach($rows as $row) {
        $company = $row['companyname'];
        $company_row_counts[$company] = isset($company_row_counts[$company]) ? $company_row_counts[$company] + 1 : 1;
    }
    
    // 循环输出表格行,处理合并单元格
    $current_company = '';
    foreach($rows as $row) {
        $companyname = $row['companyname'];
        $ordernumber = $row['ordernumber'];
        $equipment = $row['equipment'];
        $theserial = $row['theserial'];
        $type = $row['type'];
        $theaddress = $row['theaddress'];
    
        echo '<tr>';
        // 仅当公司名称变化时,输出带rowspan的单元格
        if($companyname !== $current_company) {
            echo '<td rowspan="' . $company_row_counts[$companyname] . '">' . $companyname . '</td>';
            $current_company = $companyname;
        }
        // 输出其他列内容
        echo '<td>' . $ordernumber . '</td>';
        echo '<td>' . $equipment . '</td>';
        echo '<td>' . $theserial . '</td>';
        echo '<td>' . $type . '</td>';
        echo '<td>' . $theaddress . '</td>';
        echo'</tr>';
    }
    ?>
    

说明

  • 排序是关键:如果同公司的记录不连续,合并单元格会错乱
  • rowspan属性值对应该公司的总记录数,确保单元格能覆盖所有同公司的行
  • 循环时通过$current_company变量跟踪当前公司,避免重复输出同一公司名称

内容的提问来源于stack exchange,提问作者Youngbuck2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 15:47:28