dtpf76658 2012-03-22 11:08
浏览 68
已采纳

借助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>

Scenario is so simple:

Mysql data return 6 no of records from for-each loop the result will be show like this image

enter image description here

Same way the Mysql data return 3 no of records the result will be show like this image

enter image description here

  • 写回答

5条回答 默认 最新

  • dongyi1921 2012-03-22 11:36
    关注

    Something like this, maybe

    function create_table()

    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.

    Call it like this:

    echo create_table($data);
    

    Output

    (example for 7, 4, 3 and 8 id's) enter image description here

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度