如何在循环中分配左侧的空格

时间:2013-09-21 22:27:40

标签: php

我是PHP的新人我正在制作一个程序,这将显示右侧的半金字塔与哈希。现在我的金字塔显示在左侧。它位于我的代码下方。

代码

<form method="post">
 Height: <input type="number" name="height"/> 
</form>
<?php 
$height=$_POST['height'];
if($height <= 0){echo "Please write Positive Number";}
 $spacing=$height -1; 
 $hashes=2; 

for ($i=0; $i<$height; $i++) 
{ 
    for ($j=$spacing; $j>0; $j--) 
    { 
        echo " "; 
    } 
    for ($k=0; $k<$hashes; $k++) 
    { 
       echo "#"; 
    } 
    $spacing--; 
    $hashes ++; 
    echo "<br/>"; 

}

  ?>

上述代码的结果如果高度为8。

##
###
####
#####
######
#######
########
#########

但我需要这个结果,我将在下面展示。

        ##
       ###
      ####
     #####
    ######
   #######
  ########
 #########

任何人都知道如何在左侧分配空格如上面的示例我想要的东西。其他我不需要Css来控制这个问题我想用循环来处理这个问题。

5 个答案:

答案 0 :(得分:1)

使用此:

for ($i=0; $i<$height; $i++) 
{ 
    for ($j=$spacing; $j>0; $j--) 
    { 
        echo "&nbsp;&nbsp;"; 
    } 
    for ($k=0; $k<$hashes; $k++) 
    { 
        echo "#"; 
    } 
    $spacing--; 
    $hashes ++; 
   echo "<br/>"; 

}

&nbsp;是HTML中的不间断空格。 HTML忽略空格,这就是我们使用&nbsp;插入多个空格的原因。

答案 1 :(得分:1)

您可以使用此代码代替整个for循环:

for ($i = 1; $i <= $height; $i++)
    echo str_replace(' ', '&nbsp;', str_pad(str_repeat('#', $i), $height, ' ', STR_PAD_LEFT)) . '<br/>';

答案 2 :(得分:0)

你遇到的问题是html问题,而不是php问题。 (您的代码是正确的。)浏览器只显示一个空格字符并丢弃任何后续字符。

要么将整个php输出包装在<pre>标记中,要么必须输出&nbsp;而不是空格(如果使用等宽字体,这只是一个充分的解决方案。)< / p>

答案 3 :(得分:0)

<?php
print '<pre>';
for ($i=1; $i<= 10; $i++) {
  print str_repeat('#', $i).'<br />';
}

for ($i=1; $i<= 10; $i++) {
  print str_repeat('&nbsp;', 10-$i).str_repeat('#', $i).'<br />';
}
print '</pre>';
?>

答案 4 :(得分:0)

这是另一种解决方案:

$height = abs($_POST['height']);

// the number of characters in each row of the shape
$width = $height + 1;

// one iteration creates one row
for($i = 0; $i < $height; $i++) {

    // the number of # symbols at the end of the row
    $hashes = $i + 2;

    // we know the width and the number of hashes, so space the difference
    echo str_repeat('&nbsp;', $width - $hashes);

    // and finally output the hashes
    echo str_repeat('#', $hashes);

    echo '<br/>';
}