我想在 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模板网!