2012-11-06 55 views
-8

我遇到了创建星号金字塔的问题。 请参阅我的代码。php中的星号金字塔

<?php 

    for($i=1;$i<=5;$i++){ 
     for($j=1;$j<=$i;$j++){ 
        echo "*"; 
     } 
     echo "<br />"; 
    } 

    ?> 

结果:

* 
** 
*** 
**** 
***** 

我的问题是我会如何做,像。

* 
    * * 
    * * * 
* * * * 
* * * * * 
+0

您需要推导出打印空间,除了你正在使用打印星号的一个公式。此外,内部循环可以通过调用['str_repeat'](http://php.net/manual/en/function.str-repeat.php)来取代。 – Jon

+0

可能重复[如何使用php创建金字塔?](http://stackoverflow.com/a/12800236/1226894) – Baba

回答

9
<pre><?php 

$n = $i = 5; 

while ($i--) 
    echo str_repeat(' ', $i).str_repeat('* ', $n - $i)."\n"; 

?></pre> 
+0

评论解释了这是如何工作的? –

+0

请您在'while'后解释一下这行吗?作为一个初学者,我在理解它时有一点困难。 Thx –

+0

没有解释! –

2

使用HTML空白字符来处理空格:& nbsp;

因此,像这样:

<?php 
// pyramid height 
$height = 5; 

for($i=1;$i<=$height;$i++){ 

    for($t = 1;$t <= $height-$i;$t++) 
    { 
     echo "&nbsp;&nbsp;"; 
    } 

    for($j=1;$j<=$i;$j++) 
    { 
     // use &nbsp; here to procude space after each asterix 
     echo "*&nbsp;&nbsp;"; 
    } 
echo "<br />"; 
} 

?> 
1

试试这个

$height = 5; 

$space = $height; 
for($i = 1; $i <= $height; $i++) { 
    echo str_repeat(' ', --$space); 
    for($j=1;$j<=$i;$j++){ 
     if($j > 1) { 
      echo ' '; 
     } 
     echo '*'; 
    } 
    echo '<br />'; 
} 
1
create_pyramid("*", 5); 

function create_pyramid($string, $level) { 
    echo "<pre>"; 
    $level = $level * 2; 
    for($i = 1; $i <= $level; $i ++) { 
     if (!($i % 2) && $i != 1) 
      continue; 
     print str_pad(str_repeat($string, $i),($level - 1) * strlen($string), " " , STR_PAD_BOTH); 
     print PHP_EOL; 
    } 
} 

link上面张贴由Baba

+0

它可以作为'$ string'作为''字符串',但不会妨碍OP想要。看[这个pastebin](http://pastebin.com/0i9PMJ1t)。 – Carlos

3

内使用相同的程序<center> </center>标签!像:

<center> 
<?php 

    for($i=1;$i<=5;$i++){ 
     for($j=1;$j<=$i;$j++){ 
        echo "*"; 
     } 
     echo "<br />"; 
    } 

?> 
</center> 
0
$n = 5; 
$i = 0; 

for($i=1; $i<=$n; $i++){ 

    echo "<pre>"; 
    echo str_repeat("&nbsp;", $n-$i); 
    echo str_repeat("#&nbsp;", $i); 
}