如何在PHP中将文本文件数据分隔成数组



所以我有一个文本文件,其中包含一个问答游戏的问题和答案,每个答案都与它的问题分开,每个问题/答案组合都在自己的行上。这样的:

In which movie does Michael J. Fox play a time-travelling teenager?    Back to the Future
In 'Old School', what song does Frank try and sing at Blue's funeral.  Dust In The Wind
What hiphop heroes joined forces with Aerosmith for a new version of Walk This Way?    Run DMC
What singer's February 6 birthday is a national holiday in Jamaica?    Bob Marley
What year did Steven Page leave BNL?   2009
What is a group of turtles known as?   A pod

我试图创建一个数组,在那里我可以分开问题和答案,但它一直给我一个大小为2的数组,输出是一组所有的问题或一组所有的答案,我似乎不能进一步分开它们。以下是目前为止的内容:

$fileHandler = fopen('triviaQuestions.txt', 'r');
if ($fileHandler) {
while (($line = fgets($fileHandler)) != false) {
$line = explode("t", $line);
echo $line[0];
}
fclose($fileHandler);
}

这是我从中得到的输出:

In which movie does Michael J. Fox play a time-travelling teenager?In 'Old School', what song does Frank try and sing at Blue's funeral.What hiphop heroes joined forces with Aerosmith for a new version of Walk This Way?What singer's February 6 birthday is a national holiday in Jamaica?What year did Steven Page leave BNL?What is a group of turtles known as?

正如您所看到的,它只是将所有问题分组为$line[0],而不是将它们彼此分开。当我尝试$line[1]时,它对答案做同样的事情。

<?php
$fileHandler = fopen('triviaQuestions.txt', 'r');
if ($fileHandler) {
$ques = [];
$ans = [];
while (($line = fgets($fileHandler)) !== false) {
$line = explode("   ", $line);
// Not each anwser is seperated from its question with a tab.
// For example:
// In 'Old School', what song does Frank try and sing at Blue's funeral.  Dust In The Wind
if (!isset($line[1])) {
$line = explode("  ", $line[0]);
}
$ques[] = $line[0];
$ans[] = $line[1];
}
$counter = 0;
$str = "";
foreach ($ques as $que) {
$answer = $ans[$counter];
$counter += 1;
$str .= "Q: " . $que;
$str .= "<br />";
$str .= "A: " . $answer;
$str .= "<br />";
$str .= "<hr />";
}
echo $str;
fclose($fileHandler);
}

最新更新