2013-01-31 27 views
2

我正在嘗試使用PHP寫入文件。我正在從數組寫入數據。寫入文件時未定義的偏移量

這裏是我的代碼:

$subject = $_SESSION['subject']; 
    $section = $_SESSION['section']; 
    $exam1 = $_SESSION['exam1']; 
    $exam2 = $_SESSION['exam2']; 
    $finalexam = $_SESSION['finalexam']; 
    $average = $_SESSION['average']; 

    $studentArray = $_SESSION['stringArray']; 

    $file = $subject . "-" . $section . ".txt"; 
    $fh = fopen($file, 'a'); 
    $size = sizeof($studentArray); 
    for($i = 0; $i<$size; $i++){ 
     fwrite($fh, $studentArray[$i] . " " . $exam1[$i] . " " . $exam2[$i] . " " .  $finalexam[$i] . " " . $average[$i] . " "); 
} 

當我試圖訪問該頁面,我總是得到這樣的通知:

Notice: Undefined offset: 5 in C:\xampp\htdocs\CS120\MP\Grades.php on line 26 

第26行是在for循環的一個與fwrite的。 總是有一個通知,但代碼正確寫入文件。 有什麼可以做的,以消除/解決通知/錯誤?

+3

好,您正在使用的FWRITE沒有#5元素的數組的一個明顯,這意味着它們與您的$ studentArray大小不同。 –

+0

其中一個數組沒有索引「5」的元素,即數組只有5個或更少的元素。如果生成的文件仍然正確,那將是令人驚訝的。 –

+0

謝謝大家。我現在明白了。我會嘗試做一些事情:D – hiakoto

回答

0

您可以使用

方法1

array_key_exists('1',$studentArray); // check whether array position 1 exist in array $studentArray 

方法2

if (isset($studentArray1])){ 
    // check whether array position 1 exist in array $studentArray 
} 
+0

我用isset和它的工作。謝謝! – hiakoto

0

其中一個陣列沒有索引5。我建議在使用前使用isset()

例如,對於您的會議我會做:

$subject = isset($_SESSION['subject']) ? $_SESSION['subject'] : ''; 

samething您的陣列。在使用之前,您需要檢查數組的索引。

+0

啊!我現在明白了。謝謝!我會盡力去做一些事情。 – hiakoto

+0

它的工作!非常感謝你! :D我欠你。 – hiakoto