\ t之前的数组的回声索引

时间:2017-09-28 20:51:44

标签: php arrays

我有一个琐事问题的txt文件。我将它们分成2个数组索引,并用\ t分隔。我需要按顺序将这些问题打印给用户,并且我不知道如何在第一个\ t之前显示部分数组索引。

<?php
session_start();
$file = "trivQuestions.txt";
$result = file($file);
$_SESSION['question'] = array();
$_SESSION['correctAnswers'] = array();

var_dump($_SESSION['question']);
foreach ( $result as $content ) {

$question =  explode("\t", $content);
//    echo $question[0];
//echos all questions
var_dump($question[0]);
//echo $question[0];
//echos all answers
//echo $question[1];

}

if (isset($_POST['submit'])){


}else{
echo "Welcome to trivia! Enter your answer below.";
}
?>

1 个答案:

答案 0 :(得分:0)

由于您的文件的问题和答案由文件中每个新行的标签分隔,因此您必须先按每个新行拆分文件。之后,您将能够循环遍历文件的每一行并通过选项卡进行拆分。

从这里你可以将你拆分成一个新数组或做你想做的任何事情。

根据你的描述,在下面的代码中,我尝试演示如何使用循环这样的拆分。

$file = "trivQuestions.txt";
$result = file($file);

// before you split by \t, you have to split by each new line.
// this will get you an array with each question + answer as one value
// PHP_EOL stands for end of line. PHP tries to get the end of line by using the systems default one. you can adjust that, if it a specific
// linebreak like "\n" or something else you know of. 
$lines = explode(PHP_EOL, $result);
// var_dump($lines); <- with this you would see that you are on the right way

// setup a questions array to fill it up later
$questions = array();

// lets loop trough the lines
foreach ($lines as $line) {
    // now you can explode on tab
    $entry = explode("\t", $line);
    // according to you description the question comes first, the answer later split by tab
    // so we fill the questions array
    $questions[] = $entry[0]; // the 0 element will be the question. if you want to adress the answer, use $entry[1]. maybe you want to add this in an other array for checks? 

}

// this will give you the first question
var_dump($questions[0]);

如果我遗漏了某些内容或误解了您问题的某些部分,请告知我们。也许我可以调整这段代码,让它按照您的需要运行。