將陣列資料快速轉為 HTML 表格是後台管理、報表匯出的常見需求。本文提供一個功能完整的 XTable 類別,支援:表頭設定、多筆資料批次加入、奇偶列顏色交替、table 標籤額外屬性注入、鏈式呼叫,並附贈四種實戰範例。
<?php
class XTable {
private $titles = []; // 表頭陣列
private $rows = []; // 資料列陣列
private $colors = ['#EEEEEE', '#CCEEEE']; // 奇/偶列背景色
private $extraAttr = ''; // table 額外屬性(style, class, id...)
private $titleStyle = ''; // th 樣式
/** 設定表頭 */
public function titles(array $titles, string $style = ''): self {
$this->titles = $titles;
$this->titleStyle = $style;
return $this;
}
/** 設定奇偶列背景色 */
public function background(array $colors): self {
if (count($colors) === 2) {
$this->colors = $colors;
} elseif (count($colors) === 1) {
$this->colors = [$colors[0], $colors[0]];
}
return $this;
}
/** 單筆新增資料列 */
public function addRow(array $row): self {
$this->rows[] = $row;
return $this;
}
/** 批次新增資料列 */
public function addRows(array $rows): self {
foreach ($rows as $row) {
$this->addRow($row);
}
return $this;
}
/** 設定 table 額外屬性 */
public function extra(string $attr): self {
$this->extraAttr = $attr;
return $this;
}
/** 產生最終 HTML */
public function html(): string {
// 表頭
$thead = '';
foreach ($this->titles as $title) {
$thead .= 'titleStyle ? " style='{$this->titleStyle}'" : '') . '>' . htmlspecialchars($title) . ' ';
}
$thead .= ' ';
// 資料列
$tbody = '';
foreach ($this->rows as $i => $row) {
$bg = $this->colors[$i % 2];
$tbody .= "";
foreach ($row as $cell) {
$tbody .= '' . htmlspecialchars((string)$cell) . ' ';
}
$tbody .= ' ';
}
return "extraAttr}>{$thead}{$tbody}
";
}
}
$t1 = new XTable();
$t1->titles(['姓氏', '名字', '電話'])
->addRows([
['Garcia', 'Ivan', '888'],
['Marco', 'Alfonso', '555'],
]);
echo $t1->html();
echo '
';
$t2 = new XTable();
for ($i = 1; $i <= 10; $i += 2) {
$t2->addRow(['ODD', $i]);
$t2->addRow(['EVEN', $i + 1]);
}
$t2->background(['pink', 'gold'])
->titles(['類型', '編號'])
->extra("style='width:500px; background-color:cyan; color:navy;'");
echo $t2->html();
echo '
';
$t3 = new XTable();
for ($i = 1; $i <= 6; $i++) {
$t3->addRow(["5x{$i}", 5 * $i]);
}
$t3->background(['olive', 'maroon'])
->titles(['乘法表', '5'])
->extra("style='border:dotted red 10px; padding:4px; text-align:right; width:500px; background-color:black; color:white;'");
echo $t3->html();
echo '
';
$t4 = new XTable();
$header = ['數字'];
$row = ['#'];
for ($i = 1; $i <= 10; $i++) {
$header[] = $i;
$row[] = $i;
}
$t4->titles($header)
->addRow($row)
->background(['pink', 'gold'])
->extra("style='border:solid 1px silver; padding:4px; text-align:center; width:500px; background-color:cyan; color:navy;'");
echo $t4->html();
| 需求 | 擴充方式 |
|---|---|
支援 thead/tbody 標籤 | 修改 html() 回傳 <thead>...</thead><tbody>...</tbody> |
| 資料來源為 PDOStatement/Generator | 新增 addRowsFromIterable(iterable $data) 方法 |
| 欄位對齊/格式化(數字千分位、日期格式) | 加入 setColumnFormatters(callable[] $formatters),輸出時套用 |
| 排序/分頁/搜尋(前端 DataTables 整合) | extra() 注入 id="datatable" class="display",前端 JS 初始化 |
| 匯出 Excel/CSV | 新增 toCsv()、toExcel() 方法,複用 $this->titles、$this->rows |
XTable 以約 60 行核心程式碼,提供「資料與呈現分離、鏈式 API、樣式高度客製化」的表格產生能力。專案若需更強大的報表功能,建議遷移至 Laravel Excel、PhpSpreadsheet 或前端 DataTables.js + API 回傳 JSON 的架構,但對於「快速產生後台清單、簡易報表」,本類別已足夠好用且零依賴。