【问题标题】:Echo index of array before \t\t 之前数组的回显索引
【发布时间】:2018-03-10 17:26:34
【问题描述】:

我有一个 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.";
}
?>

【问题讨论】:

  • 您是否收到错误消息?你的输入是什么?你的输出应该是什么?您是指文字 \t 还是标签?
  • @ishegg 我没有收到错误消息。用户必须输入答案,但我需要向他们展示 txt 文件中的第一个问题。当我 var_dump 问题 [0] if 显示新行上的所有问题时,例如这是一个数组 (size=1) 0 => string 'Michael J. Fox 在哪部电影中扮演一个穿越时空的少年? (length=67) 之后还有 4 个。我需要它来显示第一个问题,当用户点击提交时转到下一个问题,依此类推
  • 哦,那根本不是你的问题所暗示的。您的代码运行良好,但您想将问题分成不同的页面。您应该编辑 Q 以使其更清晰。
  • 您能否向我们展示您的问题文件中的一些内容,以便我们知道我们在这里工作的具体内容?这将有助于更好地分析您的问题,并可能得出对您有帮助的答案。
  • @natheriel 17 每个问题和答案都由一个选项卡分隔,每个带有答案的问题都在一个新行上。迈克尔·J·福克斯在哪部电影中饰演一个穿越时空的少年?回到未来 在“老派”中,弗兰克试图在布鲁的葬礼上唱什么歌。 Dust In The Wind 哪些嘻哈英雄与 Aerosmith 联手推出了新版本的 Walk This Way?运行 DMC

标签: php arrays


【解决方案1】:

由于您的文件中有一个问题和答案,文件中的每一行都用制表符分隔,因此您必须先按每一新行拆分文件。之后,您将能够循环遍历文件的每一行并用制表符将其拆分。

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

根据您的描述,在下面的代码中,我试图演示这种带有循环的拆分是如何工作的。

$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]);

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

【讨论】:

    猜你喜欢
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 2013-11-30
    • 1970-01-01
    • 2017-12-19
    • 2018-04-27
    • 1970-01-01
    相关资源
    最近更新 更多