2016-09-27 65 views
1

我想從PHP中的文本文檔中讀取問題並將它們排序在array()中。從純文本文件中讀取問題

結果數組應該是這樣的:

print_r($questionnaire); 

array(
     'question 1' => array('yes','no'), 
     'question 2' => array('yes','no'), 
     'question 3' => array('yes','no'), 
     ...etc 
) 

我的文本文檔是:

question 1? 
yes 
no 
question 2? 
yes 
no 
question 3? 
yes 
no 

我想這一點:

$txt_doc = $_FILES['txt_doc']['tmp_name']; 

$questions_and_answers = array(); 

$handle = fopen($txt_doc, 'r') or die($txt_doc . ' : CAnt read file'); 


       $i = 0; 
       while (! feof($handle)) 
       { 
        $line = trim(fgets($handle)); 

        if(strstr($line, '?'))//its a question 
        { 
         $questions_and_answers[$i] = $line;$i++; 
        } 
        if(!strstr($line, '?')) 
        { 
         $questions_and_answers[$i][] = $line; 
        }      

       } 
+1

然後當你嘗試時會發生什麼?如果它沒有達到你的期望,可以解釋它在做什麼? –

回答

0

爲了產生輸出你想要,您需要將該問題用作$questions_and_answers中的數組鍵。如果你這樣做,$i變得不必要。你可以對你正在做的問號做同樣的檢查,當你遇到問題時,創建一個新的密鑰。然後在後續行中使用該鍵(答案),直到出現下一個問題。

while (!feof($handle)) { 
    $line = trim(fgets($handle)); 
    if (strstr($line, '?')) {       // it's a question 
     $question = $line; 
    } else {           // it's an answer 
     $questions_and_answers[$question][] = $line; 
    } 
}