PHP 中的 For 循环表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22787432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:16:03  来源:igfitidea点击:

For Loop Table in PHP

php

提问by Afnizar Nur Ghifari

I am trying to generate a table with php for loop, that lists numbers. Something like this:

我正在尝试使用 php for 循环生成一个表,其中列出了数字。像这样的东西:

1 | 2 | 3 | 4 | 5
2 | 3 | 4 | 5 | 1
3 | 4 | 5 | 1 | 2
4 | 5 | 1 | 2 | 3
5 | 1 | 2 | 3 | 4

I still have problems getting it, this is actually quite simple, but I have not been able to solve it. So far I have the following code:

我还是有问题,这其实很简单,但我一直没能解决。到目前为止,我有以下代码:

<?php
echo "<table border='1'><br />";

for ($row = 0; $row < 5; $row ++) {
   echo "<tr>";

   for ($col = 1; $col <= 4; $col ++) {
        echo "<td>", ($col + ($row * 4)), "</td>";
   }

   echo "</tr>";
}

echo "</table>";
?>

However, this only generates the following:

但是,这只会生成以下内容:

1  | 2  | 3  | 4 
5  | 6  | 7  | 8
9  | 10 | 11 | 12
13 | 14 | 15 | 16
17 | 18 | 19 | 20

Thank you, any help would be appreciated!

谢谢,任何帮助将不胜感激!

回答by remudada

<?php
echo "<table border='1'><br />";

for ($row = 0; $row < 5; $row ++) {
   echo "<tr>";

   for ($col = 0; $col < 5; $col ++) {
        echo "<td>", (($col + $row) % 5) + 1, "</td>";
   }

   echo "</tr>";
}

echo "</table>";
?>

回答by blue

echo "<table border='1'><br />";
for ( $i = 0; $i < 5; $i++ ) {
    echo "<tr>";
    for ( $j = 0; $j < 5; $j++ ) {
        echo "<td>", ($j+$i)%5+1, "</td>";
    }
    echo "</tr>";
}
echo "</table>";

回答by Hackerman

My version :

我的版本:

<?php
echo "<table border='1'><br />";
$i=1;
for ($row = 0; $row < 5; $row ++) {
  echo "<tr>";
  $cont = 0;
for ($col = $i; $col <= 5; $col ++) 
    {
     echo "<td>", ($col), "</td>";
     $cont++;
    }
if($cont < 5)
{
 for($col = 1; $col <= 5 - $cont; $col++)
 {
  echo "<td>", ($col), "</td>";
 }
 }

echo "</tr>";
$i++;
}

echo "</table>";

Codepad: http://codepad.viper-7.com/JZogNY

键盘:http: //codepad.viper-7.com/JZogNY

回答by Ali Nouman

My Version

我的版本

<?php
echo "<table border='1'><br />";

for ($row = 0; $row < 5; $row ++) {
   $k=$row;

   for ($col = 0; $col < 5; $col ++) {
        echo "<td>", (($k++)%5)+1, "</td>";
   }

   echo "</tr>";
}

echo "</table>";
?>

回答by Ruiz24

<?php

    echo '<table border="1">';
    $i = 0;
    for($i =1; $i<=5; $i++){
        echo '<tr>
            <td>'.$i.'</td>';
            $x = 0;
            for($x=1; $x<=4; $x++){
                $y = $x + $i;
                $z = ($y>5) ? $y-5 : $y;
                echo '<td>'.$z.'</td>';
            }
        echo '</tr>';
    }

    echo '</table>';
?>