嗯......我遇到了一个未定义的错误

时间:2017-02-27 10:45:49

标签: php

我正在做一个关于使用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.

任何人都可以提供帮助?请?

2 个答案:

答案 0 :(得分:0)

你使用的错误限制不是maxSubNum而是count($ subjectArray)

for ($i=0; $i < count( $subjectArray)-1; $i++) {

答案 1 :(得分: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";

        ?>