借助 PHP 和 HTML 动态创建行和列 [英] Dynamic create rows and colum with the help of PHP and HTML

查看:15
本文介绍了借助 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 动态创建行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆