从纯文本文件中读取问题

时间:2016-09-27 15:01:49

标签: php text-files

我想从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 :(得分: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;
    }
}