Php 如何使用循环在左侧指定空间
我是PHP的新手,我正在制作一个程序,这个程序将在右边用散列显示半金字塔。现在我的金字塔显示在左边。下面是我的代码 代码 但我需要下面显示的结果Php 如何使用循环在左侧指定空间,php,Php,我是PHP的新手,我正在制作一个程序,这个程序将在右边用散列显示半金字塔。现在我的金字塔显示在左边。下面是我的代码 代码 但我需要下面显示的结果 ## ### #### ##### ###### ####### ######## ######### 任何人都知道如何分配左边的空格,就像上面的例子所示,我想要什么。另外,我不需要Css来控制这个问题,我想用循环来处理这个问题。使用这个: for ($i=0; $i<$h
##
###
####
#####
######
#######
########
#########
任何人都知道如何分配左边的空格,就像上面的例子所示,我想要什么。另外,我不需要Css来控制这个问题,我想用循环来处理这个问题。使用这个:
for ($i=0; $i<$height; $i++)
{
for ($j=$spacing; $j>0; $j--)
{
echo " ";
}
for ($k=0; $k<$hashes; $k++)
{
echo "#";
}
$spacing--;
$hashes ++;
echo "<br/>";
}
($i=0;$i0;$j--)的
{
回声“;
}
对于($k=0;$k您遇到的问题是一个html问题,而不是php问题。(您的代码是正确的。)浏览器只显示一个空格字符,并放弃任何后续字符
要么将整个php输出包装在一个
标记中,要么必须输出
而不是空格(如果使用单空格字体,这只是一个足够的解决方案)。
<?php
print '<pre>';
for ($i=1; $i<= 10; $i++) {
print str_repeat('#', $i).'<br />';
}
for ($i=1; $i<= 10; $i++) {
print str_repeat(' ', 10-$i).str_repeat('#', $i).'<br />';
}
print '</pre>';
?>
这里是另一个解决方案:
$height=abs($_POST['height']);
//形状每行中的字符数
$width=$height+1;
//一次迭代创建一行
对于($i=0;$i<$height;$i++){
//行末尾的#符号数
$hashes=$i+2;
//我们知道散列的宽度和数量,所以用空格隔开差异
echo str_repeat(“”,$width-$hash);
//最后输出散列
echo str_repeat('#',$hash);
回声“
”;
}
对于
循环,您可以使用此代码而不是整个:
对于($i=1;$i)值得注意的是,如果您不使用
,字符的宽度将不会固定-因此空格可能会比哈希值窄(或者不窄,取决于字体)。
就是这样做的。抱歉使用10
…我不喜欢8
;)感谢您的快速回复。我在上面的帖子中提到,我需要右边的半金字塔。@user2802991插入两个
将解决问题。我编辑了帖子。
for ($i=0; $i<$height; $i++)
{
for ($j=$spacing; $j>0; $j--)
{
echo " ";
}
for ($k=0; $k<$hashes; $k++)
{
echo "#";
}
$spacing--;
$hashes ++;
echo "<br/>";
}
<?php
print '<pre>';
for ($i=1; $i<= 10; $i++) {
print str_repeat('#', $i).'<br />';
}
for ($i=1; $i<= 10; $i++) {
print str_repeat(' ', 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(' ', $width - $hashes);
// and finally output the hashes
echo str_repeat('#', $hashes);
echo '<br/>';
}
for ($i = 1; $i <= $height; $i++)
echo str_replace(' ', ' ', str_pad(str_repeat('#', $i), $height, ' ', STR_PAD_LEFT)) . '<br/>';