如何动态更改colspan和rowspan而不会对表结构造成损害

时间:2013-07-17 12:25:30

标签: php html arrays html-table

当我尝试动态地将行数提供给<td>时 (添加rowspan取决于db的值)我得到的表如下所示。 一个额外的列出现(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>

1 个答案:

答案 0 :(得分:0)

让我们破解你的代码......

您的数据

<?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>

希望有所帮助