首页 > 解决方案 > 有没有办法让我的 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>

桌子:

桌子

我想要的输出:

我想要的输出

标签: php

解决方案


这应该这样做。我使用 PHP 的替代语法来获得更清晰的视图代码:

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

推荐阅读