2017-02-27 52 views
-3

我在做關於使用foreach和for循環在PHP中打印表格的LAB練習。但我現在已經遇到了這個問題。嗯......我遇到了一個未定義的錯誤

The question let me to print a table like this.

這裏是我的代碼:

<?php 

     $subjects = array(
      "sem1" => array("Prog", "DP", "NF", "ENG", "SDD"), 
      "sem2" => array("IP", "DMS", "OOP", "SA"), 
      "sem3" => array("INSP", "SAP", "ITP"), 
     ); 

     //maximum number of subjects 
     $maxSubNum = 10; 

     //creating table 
     echo "<table border='1'>"; 
      //loop the array 
      foreach ($subjects as $sem => $subjectArray) { 
       //print <tr> 
       echo "<tr>"; 
       //print semeester number in <td>, bold the text 
       echo "<td><b>$sem</b></td>\n"; 
       //loop 10 times 
       for ($i=0; $i < $maxSubNum; $i++) { 
        //check if subject exists 
        if (isset($subjectArray)) { 
         //print subject in <td> 
         echo "<td>$subjectArray[$i]</td>\n"; 
        } else { 
         //print empty in <td> 
         echo "<td></td>\n"; 
        } 
       } 
       //closing <tr> 
       echo "</tr>\n"; 
      } 
     echo "</table>\n"; 

     ?> 

Finally, it warns me those notices although I can print out he table.

任何人都可以幫助嗎?請?

+0

而哪一行是32行? – arkascha

+0

只需檢查'isset($ subjectArray [$ i])'。您的循環迭代10次,而您的數組中的元素數量少於此數量。這就是爲什麼你得到undefine抵消通知 –

+0

回聲「​​$ subjectArray [$ i] \ n」; 這是行32 –

回答

0

你sem1,2和3分分別列在其中5,4,3元素。 但是,當你定義$ maxSubnum = 10時,php正在尋找其他的元素。

請嘗試以下操作。

<?php 

     $subjects = array(
      "sem1" => array("Prog", "DP", "NF", "ENG", "SDD"), 
      "sem2" => array("IP", "DMS", "OOP", "SA"), 
      "sem3" => array("INSP", "SAP", "ITP"), 
     ); 



     //creating table 
     echo "<table border='1'>"; 
      //loop the array 
      foreach ($subjects as $sem => $subjectArray) { 
       //print <tr> 
       echo "<tr>"; 
       //print semeester number in <td>, bold the text 
       echo "<td><b>$sem</b></td>\n"; 
       //don't have to loop 10 times 
       //maximum number of subjects 
       $maxSubNum = count($subjectArray); 
       for ($i=0; $i < $maxSubNum; $i++) { 
        //check if subject exists 
        if (isset($subjectArray)) { 
         //print subject in <td> 
         echo "<td>$subjectArray[$i]</td>\n"; 
        } else { 
         //print empty in <td> 
         echo "<td></td>\n"; 
        } 
       } 
       //closing <tr> 
       echo "</tr>\n"; 
      } 
     echo "</table>\n"; 

     ?> 
0

您正在使用循環不maxSubNum錯誤的限制,但數($ subjectArray)

for ($i=0; $i < count($subjectArray)-1; $i++) { 
相關問題