读取文本文件后创建 Json 数据

我正在开发在线考试系统,老师应该能够从文本文件中导入问题,其中有这样的问题


what is the capital of USA?

NewYork

*Washington

Texas


what is the Capital of UAE?

DUBAI

*ABU Dhabi

Alriadh

我想逐行浏览这个文件,如果该行包含问题的标记(?),那么我可以确定它是问题部分,找到下一个问题之前的行是这个问题的答案以及旁边有一个星号的选项它可以被认为是这个循环结束时的正确答案,我需要像这样的 JSON 数据


{"questions": {"id": "1596805341211", "type": "Multiple Choice Single Answer", "question": "what is the capital of USA? ",   "answer_options": {"1596805341213": {"marks": null, "value": "NewYork"}, "1596805363748": {"marks": null, "value": "Washington"}, "1596805372883": {"marks": "100", "value": "Texas", "selected": "Selected"}}},{"id": "1596805341212", "type": "Multiple Choice Single Answer", "question": "what is the Capital of UAE?",   "answer_options": {"1596805341213": {"marks": null, "value": "DUBAI"}, "1596805363748": {"marks": null, "value": "ABU Dhabi"}, "1596805372883": {"marks": "100", "value": "Alriadh", "selected": "Selected"}}}} 

我尝试使用这段代码,但我卡住了,我不知道如何继续


$handle = fopen("test.txt", "r");

        if ($handle) {

            $qusetions[][]=array() ;

            while (($line = fgets($handle)) !== false) {

                if( Str::contains($line, '?')==1)

                {  array_push($qusetions,$line);

                }

                else{

                  

                }



            }


            fclose($handle);

        } else {


            echo "Can not open";



        }


弑天下
浏览 91回答 1
1回答

白猪掌柜的

我希望它能解决你的问题。$questions = [];$i = 0;$questionsFile = fopen(base_path('/public/questions.txt'), 'r');while ($line = fgets($questionsFile)) {    if ($line === "\n") {        $i++;        continue;    }    if (!isset($questions['questions'][$i])){        $questions['questions'][$i] = [            'id' => rand(1596805341210, 9999999999999),            'type' => 'Multiple Choice Single Answer',            'question' => '',            'answer_options' => []        ];    }    if (preg_match("/(.)+\?/", $line)) {        $questions['questions'][$i]['question'] = $line;    } else {        $answer = [            'id' => rand(1596805341210, 9999999999999),            'marks' => null,            'value' => $line,            'selected' => false,        ];        if (preg_match("/(\*)(.)+/", $line)) {            $answer['marks'] = 100;            $answer['selected'] = true;        }        $questions['questions'][$i]['answer_options'][] = $answer;    }}fclose($questionsFile);return $questions;
打开App,查看更多内容
随时随地看视频慕课网APP