在表格中总是呼应5的倍数的单元格数(php)

问题描述 投票:1回答:1

我想做的是,当我输入一个数字时,它将在1行显示5个值的表格。但我面临的问题是,当我输入67时,它看起来不像我想要的。 我想要的是总是呼应一个5的倍数的单元格。

下面是输出结果,假设是这样的,但我的输出只显示到67,不显示表格中其余的空单元格。

Here's is the output suppose like this, but my output only show until 67, it doesn't show the rest empty cell in table

这是我输入html的代码。

<!DOCTYPE html>
<html>
<body>
<form action = "shownumber.php" method="POST">
<label>Please input the maximum number : </label><input type="number" name="Max_number" required size="20">&nbsp;&nbsp;<input type="submit"  name="submit" onclick="print_number($Max_number)"/>
</form>
</body>
</html>

这是我的php文件的代码。

<table>
<?php
$Max_number = $_POST["Max_number"];
function print_number($Max_number)
{
$x=1;
for ($col=1; $col <= 5; $col++) {
if($x <= $Max_number){
echo "<td>" . $x . "</td>";
$x++;
}
else
echo "<td></td>";
}
}
print_number($Max_number);
?>
</table>

谁能帮我解决这个问题?谢谢,我想做的是

php html css
1个回答
2
投票

您的 shownumber.php 大概应该是这样的。

<table>
<?php
function print_number($Max_number) {
        $x = 1;
        while ($x <= $Max_number) {
                echo "<tr>";
                for ($col=1; $col <= 5; $col++) {
                        echo ($x <= $Max_number)
                                ? "<td>{$x}</td>"
                                : '<td></td>';
                        $x ++;
                }
                echo "</tr>";
        }
}
print_number($_POST["Max_number"] ?? 0);
?>
</table>
  1. 你应该用 <tr> 来引用所有的行。
  2. 你应该连续打印行,直到达到最大行数为止(见while循环)。

其他一些代码风格的改进。

  1. 全局的 $Max_number=$_POST["Max_number"] 如果您可以简单地使用 $_POST["Max_number"] 作为函数参数。
  2. 将if-then语句简化为 三元运算符 以求简洁明快。
  3. 用过的 null 凝聚操作者 $_POST["Max_number"] ?? 0 以防止在提交表格时出现错误。

3
投票

您当前的代码只能打印5以内的数字,不能再多了,因为固定的 for 循环。

该循环对于打印正确的列数是没有问题的,但如果要打印多行,你就需要在该循环之外进行循环。

这个版本计算出所需的行数(通过除以所需的列数),然后循环打印每个列的正确数量。

function print_number($Max_number)
{
    $cols = 5;
    $rows = ceil($Max_number / $cols);
    $num = 1;

    for ($row = 1; $row <= $rows; $row++)
    {
        echo "<tr>";
        for ($col = 1; $col <= $cols; $col++) {
            echo "<td>";
            if($num <= $Max_number) echo $num++;
            echo "</td>";
        }
        echo "</tr>";
   }
}

演示: http:/sandbox.onlinephpfunctions.comcode5fd70054b44053bebc6ba0819111d6c12544481b。

另外 onclick="print_number($Max_number)" 在你的HTML中,可以去掉(因为1.你的表单没有这个就会成功发布回来,2.反正你不能用这种方式从JavaScript中调用PHP函数)。

© www.soinside.com 2019 - 2024. All rights reserved.