PHP模式(非常基础)[保留]

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

我使用嵌套的do-while循环在PHP中获得了这种模式:(请注意,“ +”之一在顶部,但问题是它必须为“-”。)我是大学一年级的学生,在这个论坛上我很新,所以如果我做错了什么,请原谅。

这是目标结果:

“

这是当前结果:

+ -  -  -  -  -  -  -  -  -  -  
+ + -  -  -  -  -  -  -  -  -  
+ + + -  -  -  -  -  -  -  -  
+ + + + -  -  -  -  -  -  -  
+ + + + + -  -  -  -  -  -  
+ + + + + + -  -  -  -  -  
+ + + + + + + -  -  -  -  
+ + + + + + + + -  -  -  
+ + + + + + + + + -  -  
+ + + + + + + + + + -   

感谢您的帮助!谢谢。

我的失败代码:

$a=0;           
     do {
     $a++;
     {
     $b = 0;
     do { 
         echo "+ ";
         $b++;         
     } while ($b <= $a);

     $c = 10;            
     do{
         echo "- &nbsp;";
         $c--;
     } while ($c >= $a);

     }
     echo "<br />";

} while ($a <= 9);


php loops nested-loops
1个回答
0
投票

以下两种方法均有效。

方法1:具有嵌套的do-while循环

具有简单的do-while语法的详细版本。

<?php
$total = 8;
$i = 0;
do {
        $j = 0;
        do {
                if ($j >= $i) {
                        echo '-';
                } else {
                        echo '+';
                }
                if ($j < $total) {
                        echo ' ';
                }
                $j++;
        } while ($j < $total);
        echo "<br/>\n";
        $i++;
} while ($i <= $total);

方法2:使用for循环,str_repeat和trim

具有默认php函数的精简版本。

<?php

for ($i=0, $total=8; $i<=$total; $i++) {
        echo trim(str_repeat('+ ', $i) . str_repeat('- ', $total - $i)) . "<br/>\n";
}

© www.soinside.com 2019 - 2024. All rights reserved.