2016-12-14 2 views
1

Ich verwende 3 PHP-Arrays, um eine Tabelle zu erstellen, diese drei Arrays werden verwendet, um Tabellenüberschriften zu generieren.Erstellen Tabelle mit PHP-Arrays

$array1 = array('A','B'); 
$array2 = array('S','C'); 
$array3 = array('A1','B1','C1','D1'); 

Generieren Sie eine Tabelle mit diesen Array-Werten sind Header.

Ich möchte eine Tabelle wie im Bild mit diesen drei Array erstellen.

enter image description here

+0

Sie hoffen, haben Sie eine HTML-Tabelle oder ein PHP-Array 2d? –

+0

Sind die Arrays immer diese Größe? – Machavity

+0

Nein ... wird geändert –

Antwort

1

Der folgende Code wird verwendet, um die Tabelle zu dynamisch generieren, die Sie gezeigt haben. Sie können die Werte von $ array1, $ array2 bzw. $ array3 ändern und die Tabelle wird dynamisch generiert.

<?php 

$array1 = array('A','B','C'); 
$array2 = array('S','C','M'); 
$array3 = array('A1','B1','C1','D1','E1','F1'); 
/* Get the length of all arrays */ 
$lengthArray1 = count($array1); 
$lengthArray2 = count($array2); 
$lengthArray3 = count($array3); 
?> 

<table border="1" width="50%"> 
    <thead> 
     <!-- Print the header --> 
     <tr> 
      <!-- For first empty space --> 
      <td></td> 
      <?php 
      /* Based on the length of the array display the headers */ 
      for($i = 0; $i < $lengthArray1; $i++){ ?> 
       <!-- Align center and add the colspan wrt to $array length --> 
       <td colspan="<?php echo $lengthArray2; ?>" align="center"> 
        <?php echo $array1[$i]; ?> 
       </td> 
      <?php 
      } ?> 
     </tr> 
     <tr> 
      <!-- For first empty space --> 
      <td></td> 
      <?php 
      /* Loop through all the $array1 so that that many $array2 values will be assigned to $array1 header */ 
      for($i = 0; $i < $lengthArray1; $i++){ 
       for($j = 0; $j < $lengthArray2; $j++){ 
      ?> 
       <td align="center"> 
        <?php echo $array2[$j]; ?> 
       </td> 
      <?php 
       } 
      } ?> 
     </tr> 
    </thead> 
    <tbody> 
     <!-- Loop through $array3 --> 
     <?php 
     for($i = 0; $i < $lengthArray3; $i++){ ?> 
      <tr> 
       <!-- Print $array3 value in first td --> 
       <td><?php echo $array3[$i]; ?></td> 
       <?php 
       /* To get the remaining td's I have multiplied $array1 X $array2 */ 
       for($j = 0; $j < ($lengthArray1 * $lengthArray2); $j++){ 
       ?> 
       <td></td> 
       <?php 
       } 
       ?> 
      </tr> 
     <?php 
     } ?> 
    </tbody> 
</table> 
+0

'

' füge das zu deinem Tag hinzu. sieht besser aus :) – Blueblazer172

+0

@ Blueblazer172 Danke für Ihre Eingaben. Ya, das hatte ich auch gedacht. Ich habe es verlassen, so dass niemand eine Frage auf Inline-CSS stellen muss, ist ein schlechter Ansatz. Also dachte ich, lass den Benutzer das CSS so handhaben, wie er es braucht. Ich habe hinzugefügt mit = "50%" nur um zu zeigen, wie die Tabelle aussieht. –