微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法使我的PHP输出以表格形式出现? (它必须处于while嵌套循环中)

具体来说,我想要一个基于用户输入的乘法表.我只需要一张表,因为输出已经正确了.
假设我的输入乘数是2.

这是我尝试做表时的代码.

<!DOCTYPE html>
<html>
<head>
<title> Multiplication Table </title>
</head>

<body>
<form method="POST" action="#">
Enter Multiplier: <input type="text" name="mult"> <br>
<input type="submit" name="m" value="Multiply">
</form>
<table border="1">
<?PHP
if(isset($_POST["m"])){
        $mult = 0;
        $x = 1;
        $mulpli = 1;
        $pro = 0;

        $mult=$_POST["mult"];

    while($mulpli <= $mult)
    {
        echo "<tr>". "<th>". " ";
        echo "<th>". $mulpli;
        while($x <= $mult)
        {
            $pro=$x*$mulpli;
            echo "<tr>";
            echo "<th>". $x;
            echo "<th>". $pro; 
            $x=$x+1;
        }
        $x = $x-$mult;
        $mulpli=$mulpli+1;
    }
    }
?>
</th></th></tr></th></th></tr>
</table>

</body>
</html>

表:

table

我想要的输出

My desired output

解决方法:

这应该做.我使用PHPalternative syntax来获得更清晰的查看代码

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Multiplication Table</title>
    <style type="text/css">
        table, th, td { border: 1px solid black; }
        th, td { text-align: center; }
    </style>
</head>

<body>
<form method="post">
    <label>Enter multiplier limit: <input type="text" name="limit"></label>
    <button type="submit">Show Table</button>
</form>

<?PHP if (isset($_POST['limit'])):
    $limit = max(1, (int)$_POST['limit']);
?>
    <table>
        <tr>
            <?PHP for ($x = 0; $x <= $limit; $x++): ?>
            <th scope="col"><?= $x ?: '' ?></th>
            <?PHP endfor ?>
        </tr>
        <?PHP for ($y = 1; $y <= $limit; $y++): ?>
        <tr>
            <th scope="row"><?= $y ?></th>
            <?PHP for ($x = 1; $x <= $limit; $x++): ?>
            <td><?= $y * $x ?></td>
            <?PHP endfor ?>
        </tr>
        <?PHP endfor ?>
    </table>
<?PHP endif ?>

</body>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐