【问题标题】:Drawing a Pattern with Nested Loops using PHP使用 PHP 绘制带有嵌套循环的模式
【发布时间】:2018-08-10 03:52:11
【问题描述】:

我正在尝试创建一个倒置的半金字塔。金字塔需要有一个介于 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>

【问题讨论】:

    标签: php for-loop while-loop


    【解决方案1】:

    这样做的简洁方法是

    $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 --;
    }
    

    【讨论】:

    • 感谢您向我解释这一点。这样更容易理解。 @joelrosenthal
    猜你喜欢
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 2015-11-10
    • 2019-07-15
    相关资源
    最近更新 更多