0

我有一个网页(从 PHP 文件中创建)需要显示一个 30 行长的表格,并允许用户为 30 行中的每一行输入值,然后按一个按钮让 php 处理他们输入的内容。

无论如何,不​​必用一个有 30 行的表格写出一个普通的 HTML 表单,我想知道他们是否有任何方法可以用更少的代码在 PHP 中创建这个表格。

所以它看起来像

<form name="createtable" action="?page=createtable" method="POST" autocomplete="off">
    <table border='1'>
        <tr>
            <th> Weight </th>
            <th> CBM Min </th>
            <th> CBM Max </th>
            <th> Min </th>
        </tr>
        <tr>
            <th> 1000 </th>
            <th> 0.1 </th>
            <th> 2.3 </th>
            <th> <input type=text name=min1> </th>
        </tr>
        <tr>
            <th> 1500 </th>
            <th> 2.31 </th>
            <th> 3.5 </th>
            <th> <input type=text name=min2> </th>
        </tr>
        <tr>
            <th> 2000 </th>
            <th> 3.51 </th>
            <th> 4.6 </th>
            <th> <input type=text name=min3> </th>
        </tr>
            ..... + 27 more rows
    </table>
</form>

我目前只是像上面一样写出完整的表格,重量、cbm min 和 max 的值没有以标准速率增加,所以我猜正常循环不起作用,这些值可以放入数组中吗?我的 php 很生锈

4

2 回答 2

2

这是一个可能的解决方案。

/* this should contain all rows, a resultset from a database,
   or wherever you get the data from */
$rows = array(
    array(
      'weight' => 1000,
      'cbm_min' => 0.1,
      'cbm_max' => 2.3
    ),
    array(
      'weight' => 1500,
      'cbm_min' => 2.31,
      'cbm_max' => 3.5
    ),
    array(
      'weight' => 2000,
      'cbm_min' => 3.51,
      'cbm_max' => 4.6
    )
); 

?>
<form name="createtable" action="?page=createtable" method="POST" autocomplete="off">
  <table border='1'>
    <tr>
      <th> Weight </th>
      <th> CBM Min </th>
      <th> CBM Max </th>
      <th> Min </th>
    </tr>
<?php
$i = 1; // I'll use this to increment the input text name
foreach ($rows as $row) {
  /* Everything happening inside this foreach will loop for
     as many records/rows that are in the $rows array. */
 ?>
    <tr>
      <th> <?= (float) $row['weight'] ?> </th>
      <th> <?= (float) $row['cbm_min'] ?> </th>
      <th> <?= (float) $row['cbm_max'] ?> </th>
      <th> <input type=text name="min<?= (float) $i ?>"> </th>
    </tr>
  <?php
  $i++;
}
?>
  </table>
</form>
<?php
// Continue executing PHP
于 2013-08-28T20:46:06.507 回答
0

你绝对可以使用 PHP

您将需要一个 2D 数组来包含所有要在您的所有<tr>*中显示的值,<th>即 30 * 3 在您的情况下,因为第三列将包含<input>

很容易找到声明数组和编写 for 循环的语法。

for($i=0;$i<30;$i++)
{
for($j=0;$j<4;$j++)
{
    echo "<td>array[$i][$j]</td>"
}
echo "<input>...</input>"
}
于 2013-08-28T20:48:41.393 回答