如何在不损害表结构的情况下动态更改列跨度和行跨度


How to change colspan and rowspan dynamically without causing harm to table structure

当我尝试将rowspan动态赋予<td>时(添加rowspan取决于数据库中的值)我得到的表如下。出现了一个我不想要的额外列(3:::3,4::::3)。如何阻止此额外列的出现?

<?php
 $time = array (
  "06.00 - 07.00",
  "07.00 - 08.00",
  "08.00 - 09.00",
  "09.00 - 10.00",
  "10.00 - 11.00",
  "11.00 - 12.00",
  "12.00 - 01.00",
  "01.00 - 02.00",
  "02.00 - 03.00",
  "03.00 - 04.00"
 );
?>
<table border = "1">
 <tr><th>time</th><th>room1</th><th>room2</th><th>room3</th></tr>
<?php
 for ($i = 1; $i <= 10; $i++) {
?>
 <tr>
  <td><?php echo $time [$i - 1]; ?></td>
<?php
  for ($j = 1; $j <= 3; $j++) {
?>
  <td<?php if (($i == 2) && ($j == 3)) {echo ' rowspan="3"';} ?>><?php echo $i . "::::" . $j; ?></td>
<?php
  }
?>
 </tr>
<?php
 }
?>
</table>

让我们破解您的代码。。。

您的数据

<?php
  $times  = array(
    "06.00 - 07.00",
    "07.00 - 08.00",
    "08.00 - 09.00",
    "09.00 - 10.00",
    "10.00 - 11.00",
    "11.00 - 12.00",
    "12.00 - 01.00",
    "01.00 - 02.00",
    "02.00 - 03.00",
    "03.00 - 04.00"
  );
?>

执行foreach循环并渲染表

<table border = "1">
  <tr>
    <th>time</th>
    <th>room1</th>
    <th>room2</th>
    <th>room3</th>
  </tr>
<?php
  $rowspan  = 3; // number of rows to cover
  $row  = 2; // starting from row number
  $col  = 3; // starting from col number
  foreach( $times as $i => $time ) {
    $i++;
    echo '<tr>';
    echo '<td>'.$time.'</td>';
    for( $j = 1; $j <= 3; $j++ ) {
      if ( $i === $row && $j === $col ) {
        echo '<td rowspan="'.$rowspan.'">'.$i."::::".$j.'</td>';
        continue;
      }
      if ( $i > $row && $i < ( $rowspan + $row ) && $j === $col ) {
        continue; // We don't need those extra columns, so continue
      }
      echo '<td>'.$i."::::".$j.'</td>';
    }
    echo '</tr>';
  }
?>
</table>

希望它能帮助