2016-09-27 45 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; 
    } 
}