php数组实现表格

使用PHP数组生成HTML表格
PHP数组可以方便地转换为HTML表格,以下是几种常见实现方式:
基础数组转表格
$data = [
['Name', 'Age', 'City'],
['John', 25, 'New York'],
['Jane', 30, 'London'],
['Mike', 22, 'Paris']
];
echo '<table border="1">';
foreach ($data as $row) {
echo '<tr>';
foreach ($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</table>';
关联数组转表格
$users = [
['name' => 'John', 'age' => 25, 'city' => 'New York'],
['name' => 'Jane', 'age' => 30, 'city' => 'London'],
['name' => 'Mike', 'age' => 22, 'city' => 'Paris']
];
echo '<table border="1"><tr>';
foreach (array_keys($users[0]) as $header) {
echo '<th>'.ucfirst($header).'</th>';
}
echo '</tr>';
foreach ($users as $user) {
echo '<tr>';
foreach ($user as $value) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</table>';
使用函数封装表格生成
function arrayToTable(array $data, $headers = null) {
$html = '<table border="1">';
if ($headers) {
$html .= '<tr>';
foreach ($headers as $header) {
$html .= '<th>'.$header.'</th>';
}
$html .= '</tr>';
}
foreach ($data as $row) {
$html .= '<tr>';
foreach ($row as $cell) {
$html .= '<td>'.$cell.'</td>';
}
$html .= '</tr>';
}
$html .= '</table>';
return $html;
}
$data = [
[1, 'Apple', 0.99],
[2, 'Orange', 1.25],
[3, 'Banana', 0.50]
];
echo arrayToTable($data, ['ID', 'Product', 'Price']);
从数据库结果生成表格
// 假设$result是PDO查询结果
$result = $pdo->query("SELECT * FROM products");
echo '<table border="1"><tr>';
for ($i = 0; $i < $result->columnCount(); $i++) {
$meta = $result->getColumnMeta($i);
echo '<th>'.$meta['name'].'</th>';
}
echo '</tr>';
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</table>';
添加CSS样式
$data = [
['Quarter', 'Revenue'],
['Q1', 15000],
['Q2', 22000],
['Q3', 18000],
['Q4', 25000]
];
echo '<style>
.data-table { border-collapse: collapse; width: 100%; }
.data-table th, .data-table td { border: 1px solid #ddd; padding: 8px; }
.data-table th { background-color: #f2f2f2; text-align: left; }
.data-table tr:nth-child(even) { background-color: #f9f9f9; }
</style>';
echo '<table class="data-table">';
foreach ($data as $row) {
echo '<tr>';
foreach ($row as $cell) {
echo (is_string($cell) && $row === $data[0]) ? '<th>'.$cell.'</th>' : '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</table>';
这些方法展示了如何将PHP数组转换为HTML表格,从简单实现到更复杂的样式处理,可以根据实际需求选择适合的方式。







