首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 陣列輸出 HTML 表格類別:支援斑馬紋、自訂樣式、多組資料

     編輯:PHP 相關知識

前言

將陣列資料快速轉為 HTML 表格是後台管理、報表匯出的常見需求。本文提供一個功能完整的 XTable 類別,支援:表頭設定、多筆資料批次加入、奇偶列顏色交替、table 標籤額外屬性注入、鏈式呼叫,並附贈四種實戰範例。

XTable 類別完整實作

<?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}
"; } }

四種實戰範例

範例 1:基本員工名單

$t1 = new XTable();
$t1->titles(['姓氏', '名字', '電話'])
   ->addRows([
       ['Garcia', 'Ivan', '888'],
       ['Marco', 'Alfonso', '555'],
   ]);
echo $t1->html();
echo '
';

範例 2:自訂顏色與寬度

$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 '
';

範例 3:乘法表(深色主題)

$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 '
';

範例 4:單列多欄(橫向資料)

$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 的架構,但對於「快速產生後台清單、簡易報表」,本類別已足夠好用且零依賴。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved