<?php
echo "<ul>";
for ($i = 1; $i <= 5; $i++) {
$color = ($i % 2 === 0) ? 'yellow' : 'red';
echo "<li style='background:{$color}; width:200px;'>這是第 {$i} 行</li>";
}
echo "</ul>";
?>
<style>
.table-striped tbody tr:nth-child(odd) { background: #f9f9f9; }
.table-striped tbody tr:nth-child(even) { background: #eef; }
</style>
<table class="table-striped">
<tbody>
<?php for ($i=1; $i<=5; $i++): ?>
<tr><td>第 <?= $i ?> 行資料</td></tr>
<?php endfor; ?>
</tbody>
</table>
優點:HTML 乾淨、無 PHP 邏輯耦合、瀏覽器原生渲染、支援動態增減列。
<?php
class TableHelper {
public static function render(array $rows, array $columns, $oddClass='odd', $evenClass='even') {
echo "<table><thead><tr>";
foreach ($columns as $col) echo "<th>{$col}</th>";
echo "</tr></thead><tbody>";
foreach ($rows as $i => $row) {
$class = ($i % 2 === 0) ? $oddClass : $evenClass;
echo "<tr class='{$class}'>";
foreach ($columns as $col) echo "<td>".htmlspecialchars($row[$col] ?? '')."</td>";
echo "</tr>";
}
echo "</tbody></table>";
}
}
// 使用
$data = [
['id'=>1, 'name'=>'張三', 'age'=>20],
['id'=>2, 'name'=>'李四', 'age'=>22],
];
TableHelper::render($data, ['id','name','age']);
?>
:root {
--row-odd: #fff;
--row-even: #f0f4ff;
}
tr:nth-child(odd) { background: var(--row-odd); }
tr:nth-child(even) { background: var(--row-even); }
nth-child,最簡潔高效