問題描述
我想在 PHP 和 HTML 的幫助下創建動態行和列,但我對這段代碼有點困惑,所以絕對感謝一些幫助.
I want to create dynamic rows and column with the help of PHP and HTML but I am little confused about this code so some help is definitely appreciated.
<table>
<?php
$tr = 0;
foreach ($data as $db_data) {
$tr++;
if ($tr == 1) {
echo "<tr>";
}
echo "<td>";
echo $db_data['id'];
echo "</td>";
}
if($tr == 2){
}
?>
</table>
場景就這么簡單:
Mysql 數據從 for-each 循環返回 6 條記錄,結果將顯示如下圖
Mysql data return 6 no of records from for-each loop the result will be show like this image
同理,Mysql數據返回3條記錄,結果如下圖
Same way the Mysql data return 3 no of records the result will be show like this image
推薦答案
可能是這樣的
function create_table($data) {
$res = '<table width="200" border="1">';
$max_data = sizeof($data);
$ctr = 1;
foreach ($data as $db_data) {
if ($ctr % 2 == 0) $res .= '<td align="center">' . $db_data['id']. '</td></tr>';
else {
if ($ctr < $max_data) $res .= '<tr><td align="center">' . $db_data['id']. '</td>';
else $res .= '<tr><td colspan="2" align="center">' . $db_data['id']. '</td></tr>';
}
$ctr++;
}
return $res . '</table>';
}
當然,您可以根據需要修改表格樣式.
Course, you can modify style of table to fit your needs.
這樣稱呼它:
echo create_table($data);
輸出
(7、4、3 和 8 id 的示例)
如果傳遞偶數個 id,則返回每列中行數相同的表,或者如果將奇數個 id 傳遞給函數,則返回最后一行合并的表.
It returns table with same number of rowsin each column if you pass even number of id's or table where last row is merged if you pass odd number of id's into function.
這篇關于借助 PHP 和 HTML 動態創建行和列的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!