\t之前的数组的回声索引 [英] Echo index of array before \t

查看:35
本文介绍了\t之前的数组的回声索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a txt file of trivia questions. I have split them into 2 array indexes and are seperated with a \t. I need to print those questions to the user in order and I don't know how to display part of the array index before the first \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.";
}
?>


推荐答案

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

As your file has a question and answer separated by a tab on each new line in the file, you will have to split your file by each new line first. After that you will be able to loop trough each line of the file and split it by a tab.

在这里,您可以将您拆分成一个新数组,或使用它进行任何操作。

From here you could add you split into a new array or do whatever you want to do with it.

根据您的描述,在下面的代码中,我试图演示如何使用循环进行拆分。

In the code below I tried to demonstrate how such a split with loop would work, according to your description.

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

如果我错过了某些事情或对您的问题有误解,请告诉我。也许我可以调整此代码,以使其按需使用。

If I have missed something or misunderstood parts of your question, let me know. Maybe I can adjust this code, to make it work as you need it to be.

这篇关于\t之前的数组的回声索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆