如何利用数组实现表格colspan,通过HTML/PHP在TCPDF中生成指定格式的TOP10损失时长表格
实现方案
你需要的是同设备名(NAMA MESIN)行首单元格合并的分组表格,用HTML+数组分组实现最方便,TCPDF原生支持HTML的rowspan合并属性,直接生成HTML后调用writeHTML方法渲染即可,完整修改代码如下:
// THIRD TABLE 原有查询逻辑不变 $pdf->AddPage(); $pdf->SetFillColor(235, 234, 230); $pdf->SetFont('times','BI',8); $sql = "SELECT * FROM (SELECT merk_tmp,rusak_tmp,COUNT(merk_tmp) as frek,SUM(durasi_tmp) as durasimenit, round((SUM(durasi_tmp)/60),1) as durasijam, ROW_NUMBER() over (PARTITION BY merk_tmp ORDER BY durasimenit DESC) as country_rank, round((SUM(durasi_tmp) / COUNT(merk_tmp)),0) as avg FROM tb_tmp WHERE 1"; if(!empty($from) && !empty($end)){ $sql .=" AND waktu_tmp BETWEEN '".$from."' and '".$end."'"; } if(!empty($mesin)){ $sql .= " AND merk_tmp = '".$mesin."'"; } $sql .=" GROUP BY rusak_tmp ORDER BY merk_tmp asc, country_rank ASC) ranks WHERE country_rank <= 10"; $query= mysqli_query($connect, $sql); // 新增:按设备名分组整理数据 $machineGroup = []; while ($data = mysqli_fetch_array($query)) { $machineName = $data['merk_tmp']; if (!isset($machineGroup[$machineName])) { $machineGroup[$machineName] = []; } $machineGroup[$machineName][] = $data; } // 构建带合并样式的HTML表格 $html = <<<EOD <style> table { border-collapse: collapse; width: 290px; font-family: times; font-size: 8px; } .title { background-color: #ebeae6; font-weight: bold; font-style: italic; text-align: center; padding: 5px; border: 1px solid #000; } th { background-color: #e0ebff; font-weight: bold; text-align: center; border: 1px solid #000; padding: 5px; } td { border: 1px solid #000; padding: 7px; text-align: center; } .machine-col { text-align: left; } .work-col { text-align: left; } </style> <table> <tr><td colspan="8" class="title">TOP 10 LOST TIME TOP</td></tr> <tr> <th width="80px">NAMA MESIN</th> <th width="20px">FREK</th> <th width="70px">JENIS PEKERJAAN</th> <th width="35px">DURATION (Minutes)</th> <th width="35px">DURATION (Hours)</th> <th width="20px">PERINGKAT</th> <th width="15px">%</th> <th width="15px">AVG</th> </tr> EOD; // 遍历分组数据生成表格行 foreach ($machineGroup as $machineName => $itemList) { $rowNum = count($itemList); $isFirst = true; foreach ($itemList as $item) { $html .= "<tr>"; if ($isFirst) { // 首行输出合并后的设备名列 $html .= "<td class='machine-col' rowspan='{$rowNum}'>{$machineName}</td>"; $isFirst = false; } // 输出其余列数据 $html .= "<td>{$item['frek']}</td>"; $html .= "<td class='work-col'>{$item['rusak_tmp']}</td>"; $html .= "<td>{$item['durasimenit']}</td>"; $html .= "<td>{$item['durasijam']}</td>"; $html .= "<td>{$item['country_rank']}</td>"; // 若需要计算真实百分比,可提前统计总时长后替换此处数值 $html .= "<td>{$item['durasijam']}</td>"; $html .= "<td>{$item['avg']}</td>"; $html .= "</tr>"; } } $html .= "</table>"; // 渲染HTML到PDF $pdf->writeHTML($html, true, false, true, false, '');
注意事项
- 列宽完全沿用你原来设置的像素值,渲染效果和原生Cell调用一致,可根据实际打印效果调整
- 如果需要百分比列显示真实占比,只需提前统计所有记录的总时长,每条数据对应时长除以总时长即可
- 后续调整样式只需修改CSS部分,比手动调用Cell/
MultiCell接口维护成本低很多
内容的提问来源于stack exchange,提问作者vivie
相关产品推荐
相关产品推荐

