3
for ($i=1; $i<=4; ++$i) {
    echo "The number is " . $i . "\n";
}

这将输出:

The number is 1
The number is 2
The number is 3
The number is 4

我怎样才能制作一个循环来给我这样的输出:

The number is 1
The number is 1
The number is 1
The number is 1
The number is 2
The number is 2
The number is 2
The number is 2
etc 

谢谢你的帮助。

4

7 回答 7

7

没有嵌套循环:这对于单个循环就足够了。

for($i=0;$i<9*4;$i++)
{
    echo "The number is ".(1+floor($i/4));
}
于 2012-06-29T23:36:52.960 回答
4

所以你要

for ($i=1; $i<=2; ++$i) {
    echo "The number is " . $i . "\n";
    echo "The number is " . $i . "\n";
    echo "The number is " . $i . "\n";
    echo "The number is " . $i . "\n";
}

但是让我们避免循环重复!

for ($i=1; $i<=2; ++$i) {
    for ($j=1; $j<=4; ++$j) {
        echo "The number is " . $i . "\n";
    }
}
于 2012-06-29T23:37:54.553 回答
3

您需要两个嵌套循环,如下所示:

for( $i = 1; $i <= 4; ++$i) { 
    for( $j = 1; $j <= 4; ++$j) {
        echo "The number is " . $i . "\n"; 
    }
}
于 2012-06-29T23:36:19.203 回答
3

本质上,您想在循环内打印四次......所以您可以编写四个 echo 语句。更好的方法是使用嵌套的 for 循环。

for ($i=1; $i<=4; ++$i) {
    for ($j=1; $j<=4; ++$j) {
        echo "The number is " . $i . "\n";
    }
}

对于外部循环的每次迭代,内部循环都会打印该语句四次。使用嵌套循环要小心的一件事是条件中使用的变量。如果你把它们混在一起,你可能会遇到奇怪的问题,包括无限循环。

于 2012-06-29T23:38:03.527 回答
3

一百万种可能的解决方案之一可能是使用单循环和str_repeat()函数。

for ($i=1; $i<=4; $i++)
  echo str_repeat("The number is $i\n", 4);

这可能是对同一字符串进行多次重复的最佳方式。

于 2012-06-30T00:00:26.587 回答
2

你可以做两个循环

for($i = 1; $i <= 4; $i++) {
    for($j = 1; $j <= 4; $j++) {
        echo 'The number is '.$i."\n";
    }
}
于 2012-06-29T23:36:59.653 回答
1

您有相同的循环,但其中有四次迭代:

for ($i=1; $i<=4; ++$i) {
    for($j=0;$j<4;$j++) {
        echo "The number is " . $i . "\n";
    }
}
于 2012-06-29T23:36:42.337 回答