如何使用循环在左侧分配空格


How to assigns spaces on left side with loop

我是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 来控制这个问题,我想用循环来处理这个想法。

使用这个:

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;来插入多个空格。

您可以使用

此代码代替整个for循环:

for ($i = 1; $i <= $height; $i++)
    echo str_replace(' ', '&nbsp;', str_pad(str_repeat('#', $i), $height, ' ', STR_PAD_LEFT)) . '<br/>';
<?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>';
?>

这是另一个解决方案:

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

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

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