php - 使用 PHP 绘制带有嵌套循环的图案

标签 php for-loop while-loop

我正在尝试创建一个颠倒的半金字塔。金字塔需要有一个 1 到 20 之间的随机数。金字塔顶部会有一个刷新按钮,单击该按钮时,它将生成一个新的 rand(1,20) 金字塔模式。它看起来像这样

****
 ***
  **
   *

我不知道我是否正确地为 PHP 编写了代码。一些指导会很棒。

PHP 代码如下

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <h2>Drawing a Pattern with Nested Loops</h2>
        <input type="submit" value="Refresh" onclick=""window.location.reload()"/>
        <?php

            $star = rand(1,20);
            $row = 1;
            $col =1;

               while($row <= $star) {
                   for($col = 1; $col < $row; $col++)
                   {
                       echo " * ";
                   }
                   echo "<br>";
                   $col--;
               }
   </body>
</html>

最佳答案

执行此操作的简洁方法是

$star = rand(1,20);
while($star) {
   echo str_repeat('*', $star) . '<br>';
   $star --;
}

但是如果您需要使用嵌套循环,您可以将 str_repeat 替换为如下所示的循环

$star = rand(1,20);
while($star) {
    for ($i = 0; $i < $star; $i++) {
        echo '*';
    }
    echo '<br>';
    $star --;
}

虽然我认为 foreach 会更干净

$star = rand(1,20);
while($star) {
    foreach(range(1,$star) as $index) {
        echo '*';
    }
    echo '<br>';
    $star --;
}

关于php - 使用 PHP 绘制带有嵌套循环的图案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49060534/

相关文章:

php - 将数据库中的用户 ID 添加到 Codeigniter 中的 session 数据?

php - Zend Action Helper 未加载*有时*

python - 在Python中将奇数移动到列表的末尾,奇怪的结果

c - if 条件中的 i++ 和 while 循环内 if 后的 i++ 有什么区别?

c++ - 如何解决这个奇怪的 while 循环错误?

php - 为什么 Eclipse 代码完成在某些项目上不起​​作用?

php - Mysql UPDATE 有时有效?

c++ - 调用 for 循环条件 (c++)

javascript - 使用 for 循环来识别 html .classes (jQuery)

php - 循环遍历 MySQL 结果