2014-04-01 11 views
11

Ich versuche, eine Tabelle mit PHP for Loop zu generieren, die Nummern auflistet. Etwas wie folgt aus:For Loop-Tabelle in PHP

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 

ich immer noch Probleme haben, bekommen es, das ist eigentlich ganz einfach, aber ich habe nicht in der Lage gewesen, es zu lösen. Bisher habe ich den folgenden Code haben:

<?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>"; 
?> 

Dies ist jedoch erzeugt nur die folgenden:

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

Danke, wäre jede Hilfe dankbar!

+2

Dies sollte g Ive Sie eine Idee '$ a = Array (1,2,3,4,5); array_unshift ($ a, array_pop ($ a)); ' –

+1

Dies wird in Datenstrukturen" Warteschlange "genannt. Lesen Sie diese http://www.phpmoot.com/other-sorting-options/ –

+0

Keine Warteschlange ... riecht wie modulare Arithmetik für mich. – EthanB

Antwort

15
<?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>"; 
?> 
+0

Das ist großartig, danke – afnizarnur

6
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>"; 
3

Meine 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

2

Meine 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>"; 
?> 
0
<?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>'; 
?> 
+1

überlege, die Erklärung hinzuzufügen, anstatt den Code hinzuzufügen. –