使用PHP绘制嵌套循环模式

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

我正在尝试创建一个倒置的半金字塔。金字塔需要有一个介于1和20之间的随机数。金字塔顶部会有一个刷新按钮,当点击它时,它将生成一个新的兰特(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>
php for-loop while-loop
1个回答
2
投票

这样做的简洁方法是

$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 --;
}
© www.soinside.com 2019 - 2024. All rights reserved.