PHP Vertical Alphabet Using FOR Cycle

泄露秘密 提交于 2019-12-11 03:38:32

问题


I'm trying to do a script in PHP which will generate a table with vertical alphabet in it. It will simply echo letters from A to Z and when it comes to Z, it will reset and begin from A again. I have a problem with this because I only can repeat this twice, then all cells have some unwanted signs in them. I'm echo-ing the letter using their ASCII html codes, where the A sign is &#65 and the Z sign is &#90.

Here is the code I have until now, thanks for help.

<!DOCTYPE html>
<html>

<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <title>Vertical alphabet</title>
</head>
<body>
    <form method="post">
        <input type="number" placeholder="COLUMNS" name="cols" />
        <input type="number" placeholder="ROWS" name="rows" />
        <input type="submit" value="Create table" /><br><br>
    </form>

        <?php
            if(isset($_POST['rows']) && isset($_POST['cols'])) {
                $col = $_POST['cols'];
                $row = $_POST['rows'];

                echo ("<table rules='all'>");

                for($i = 1; $i<$row+1; $i++) {
                    echo ("<tr>");
                    for($c = 0; $c<$col; $c++) {
                        $letter_id = 65;
                        $number = ($i + ($c*$row)-1);
                        $letter = $number + $letter_id;
                        if($letter > 90) {
                            $number = $number - 26;
                            $letter = $letter - 26;
                            echo ("<td>". "&#" . $letter. "</td>");
                        } else {
                            echo ("<td>". "&#" . $letter. "</td>");
                        }
                    }
                    echo ("</tr>");
                }
                echo ("</table>");
            }
        ?>
</body>
</html>

回答1:


Not sure what you're trying to with the $number variable, but that's the issue here

$number = 0;

echo ("<table rules='all'>");

for($i = 1; $i<=$row; $i++) {
     echo ("<tr>");
     for($c = 0; $c<$col; $c++) {
          $letter_id = 65;
          $number = $i + ($c*$row);
          $letter = $number + $letter_id;
          while($letter > 90) {
                $letter = $letter - 26;
          }
          echo ("<td>". "&#" . $letter. "</td>");
     }
     echo ("</tr>");
}

echo ("</table>");

UPDATED:

Now vertical, try this...




回答2:


Because $number always grown up.
The first A-Z, $number is between 0 and 25, you go in the else case and it is ok.
The second A-Z, $number is between 26 and 51, you go in the if case, you remove 26 and your print is ok.

Next $number is at 52, as previously, you go in the if case and try to print the 27th letter of alphabet ^^



来源:https://stackoverflow.com/questions/29333975/php-vertical-alphabet-using-for-cycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!