从纯文本文件中读取问题


Read questions from a plain text file

我想从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;
                    }                    
                }

为了产生您想要的输出,您需要将问题用作$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;
    }
}