$info = [
'user' => [
[1, '張三', 20, '男'],
[2, '李四', 20, '男'],
[3, '王五', 25, '女'],
],
'score' => [
[1, 100, 98, 95, 96],
[2, 56, 98, 87, 84],
[3, 68, 75, 84, 79],
],
'connect' => [
[1, '2468246', 'salkh@bbs.com'],
[2, '343681643', 'aikdki@sina.com'],
[3, '3618468', '42816@qq.com'],
],
];
<?php
foreach ($info as $tableName => $table) {
echo "<table align='center' border='1' width='300'>";
echo "<caption><h3>$tableName</h3></caption>";
foreach ($table as $row) {
echo "<tr>";
foreach ($row as $col) {
echo "<td>$col</td>";
}
echo "</tr>";
}
echo "</table><br>";
}
?>
生成三張獨立表格,標題分別為 user、score、connect,行列數與數據結構完全對應。
array_keys() 輸出 <th>。border、width 移至 CSS 類,保持結構與表現分離。is_array() 校驗,避免非數組報警。yield 分批輸出,或直接輸出到瀏覽器緩衝區。
function renderTable($data, $level = 0) {
if (!is_array($data)) return htmlspecialchars($data);
$html = "<table>";
foreach ($data as $key => $val) {
$html .= "<tr><th>$key</th><td>";
$html .= is_array($val) ? renderTable($val, $level+1) : htmlspecialchars($val);
$html .= "</td></tr>";
}
$html .= "</table>";
return $html;
}
echo renderTable($info);
遞歸函數可處理任意層級嵌套,適合調試輸出複雜數據結構。