使用垂直和水平标头生成html表的动态数据

时间:2017-03-25 21:40:14

标签: php html html-table

创建一个仅包含水平标题或垂直标题的动态表非常简单。但是如何为具有BOTH垂直和水平标题的表生成动态数据?这甚至可能吗?

表格

<table>
    <tr>
        <th></th>
        <th scope="col">Monday</th>
        <th scope="col">Tuesday</th>
        <th scope="col">Wednesday</th>
        <th scope="col">Thursday</th>
        <th scope="col">Friday</th>
        <th scope="col">Saturday</th>
        <th scope="col">Sunday</th>
    </tr>
    <tr>
        <th scope="row">Week 1</th>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
    </tr>
    <tr>
        <th scope="row">Week 2</th>
        <td>2</td>
        <td>2</td>
        <td>2</td>
        <td>2</td>
        <td>2</td>
        <td>2</td>
        <td>2</td>
    </tr>
    <tr>
        <th scope="row">Week 3</th>
        <td>3</td>
        <td>3</td>
        <td>3</td>
        <td>3</td>
        <td>3</td>
        <td>3</td>
        <td>3</td>
    </tr>
    <tr>
        <th scope="row">Week 4</th>
        <td>4</td>
        <td>4</td>
        <td>4</td>
        <td>4</td>
        <td>4</td>
        <td>4</td>
        <td>4</td>
    </tr>
</table>

2 个答案:

答案 0 :(得分:1)

是的,可以在PHP中轻松完成。我做了一个使用for循环的小例子,让你更容易想到如何实现这个

<table>
    <tr>
        <th></th>
        <th scope="col">Monday</th>
        <th scope="col">Tuesday</th>
        <th scope="col">Wednesday</th>
        <th scope="col">Thursday</th>
        <th scope="col">Friday</th>
        <th scope="col">Saturday</th>
        <th scope="col">Sunday</th>
    </tr>
    <?php
        // Create week row
        for ($week = 0; $week < 10; $week++) {
            echo "            <tr>";
            echo "                <th scope='row'>Week " . $week . "</th>";

            // Create day cells
            for ($day = 0; $day <= 7; $day++) {
                echo "                <td>" . $day . "</td>";
            }

            echo "            </tr>";
        }
    ?>
</table>

答案 1 :(得分:1)

要水平和垂直动态生成表格,您需要2个循环,第一个循环用于行数,而第一个用于cols。

<?php

  $rows = 10;
  $cols = 20;

  echo '<table>';
  for($r=0; $r <= $rows; $c++){
    echo "<tr>";
    for($c=0; $c <= $cols; $r++){
      echo "<td>$r</td>";
    }
    echo "</tr>";
  }
  echo '</table>';

?>