2016-12-14 91 views
1

我使用3個php數組創建表,這三個數組用於生成表頭。使用php數組創建表

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

生成一個表,其中這些數組值是標題。

我想用這三個數組創建一個像圖像一樣的表。

enter image description here

+0

你希望有一個html表或php數組2d? –

+0

數組是否總是這樣大小? – Machavity

+0

不會...會改變 –

回答

1

下面的代碼被用於動態地生成已示出的表。您可以分別更改$ array1,$ array2或$ array3的值,並且動態生成表。

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

'

'將其添加到您的表格標記中。看起來更好:) – Blueblazer172

+0

@ Blueblazer172感謝您的輸入。雅甚至我也曾想過這一點。我離開它,所以沒有人必須提出內聯CSS的問題是一個壞方法。所以我想讓用戶以他需要的方式處理CSS。我添加了=「50%」,只是爲了顯示錶格的外觀。 –