繁体   English   中英

HTML 表格上的 PHP 数据 - 展开 HTML 表格

[英]PHP Data on HTML Table - Expand HTML Table

我想从数据库中获取数据并将其显示在 html 表中。 我的困境是,如果返回的行数超过 x 行,我需要能够扩展 html 表,如下图所示。 因此,例如,如果只返回 10 行,它们将显示在一个直表中(如第一个示例图像中所示)。 而如果说 20 被返回,它会将其中一些推到右边的第二个“桌子”(如第二个示例图像所示)。 我不确定如何使用 php 完成此操作。 如果有人可以帮助我,我将不胜感激。

我的见解

我认为我会采取的方法是将行从 MySQL 提取到两个单独的二维数组中,而不是尝试动态构建两个 HTML <table>

在 MySQL fetch 循环中,迭代每一行的列,当你超过你的数字$maxcols ,开始追加到另一个数组。 然后在完成 fetch 循环后,分别迭代这两个数组以构建 HTML 表。

有几种方法可以管理嵌套循环。 这是第一个想到的

// An array initialized for each table (will become 2D arrays)
$t1 = array();
$t2 = array();

// Max cols in the first table
$maxcols = 10;

// Your fetch loop (pseudocode since we don't know which API you use)
while ($row = $result->fetch()) {
    // New row in both table arrays
    $new_t1 = array();
    $new_t2 = array();

    // Loop over columns
    $idx = 0;
    foreach ($row as $col) {
      if ($idx < $maxcols) {
         // Index is less than maxcols, append to the first table's new row
         $new_t1[] = $col;
      }
      // >= maxcols, append to second table's new row
      else $new_t2[] = $col;

      // Increment the index
      $idx++;
    }
    // Each of the two `$new_t* arrays now comprises a complete table row
    // Append each new array as a row onto the correct table 2D array
    $t1[] = $new_t1;
    $t2[] = $new_t2;
}

然后遍历每个数组$t1, $t2以构建您的两个表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM