-1

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

我的设想

4

1 回答 1

1

我认为我将采取的方法是将行从 MySQL 获取到两个单独的 2D 数组中,而不是尝试<table>即时构建两个 HTML。

在 MySQL fetch 循环中,遍历每一行的列,当超过 number 时$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以构建您的两个表。

于 2012-11-15T00:21:43.323 回答