[英]How to convert an array to a html table
有人可以幫我解決這個問題嗎? 我想創建一個表,該表最多5列,最多15行。 例如,如果只有4行,那么應該只顯示4行而不是15行。如果只有3個具有數據的單元格,則剩余的2個單元應該用$nbsp;
填充$nbsp;
。
這是我的示例數組:
Array
(
[0] => Array
(
[name] => test1
[item_id] => 1
)
[1] => Array
(
[name] => test2
[item_id] => 2
)
[2] => Array
(
[name] => test3
[item_id] => 3
)
[3] => Array
(
[name] => test4
[item_id] => 4
)
[4] => Array
(
[name] => test5
[item_id] => 5
)
[5] => Array
(
[name] => test6
[item_id] => 6
)
)
如果添加了新行,我的數據將重復。 這是我目前的問題。
$row = count( $array ) / 5;
$col = 5;
echo'<table border="1" width="700">';
for( $i = 0; $i < $row; $i++ )
{
echo'<tr>';
for( $j = 0; $j < $col; $j++ ) {
if( ! empty( $array[$j] ) ) {
echo '<td>'.$array[$j]['item_id'].'</td>';
}
}
echo'</tr>';
}
echo'</table>';
我們將數組稱為$rows
,好嗎?
echo "<table>";
foreach ($rows as $row) {
echo "<tr>";
foreach ($row as $column) {
echo "<td>$column</td>";
}
echo "</tr>";
}
echo "</table>";
使用foreach
在php中循環槽數組更慣用,它大大提高了代碼的可讀性。 另外,您所需的唯一變量是包含數組本身的變量。
這是我編寫的用於測試將php數組轉換為html的代碼段。
$row = array(
'column 1' => 'value',
'column 2' => 'value',
'column 3' => 'value',
'column 4' => 'value',
'column 5' => 'value',
'column 6' => 'value',
'column 7' => 'value',
);
$rows = array($row, $row, $row, $row, $row, $row, $row, $row, $row, $row);
print array_to_html($rows);
function array_to_html($data) {
$report = "";
if (count($data) > 0) {
$report .= "<table>";
$report .= sprintf("<tr><th>%s</th></tr>", join("</th><th>", array_keys($data[0])));
foreach ($data as $row) {
$report .= "<tr>";
foreach ($row as $column) {
$report .= "<td>$column</td>";
}
$report .= "</tr>";
}
$report .= "</table>";
} else {
$report = "No data";
}
return $report;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.