Dynamic create rows and colum with the help of PHP and HTML(借助 PHP 和 HTML 动态创建行和列)
问题描述
我想在 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 动态创建行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:借助 PHP 和 HTML 动态创建行和列
基础教程推荐
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
