为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
弑天下 2023-09-22 14:59:28
我正在开发在线考试系统,老师应该能够从文本文件中导入问题,其中有这样的问题what is the capital of USA?NewYork*WashingtonTexaswhat is the Capital of UAE?DUBAI*ABU DhabiAlriadh我想逐行浏览这个文件,如果该行包含问题的标记(?),那么我可以确定它是问题部分,找到下一个问题之前的行是这个问题的答案以及旁边有一个星号的选项它可以被认为是这个循环结束时的正确答案,我需要像这样的 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";        }
查看完整描述

1 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

我希望它能解决你的问题。


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


查看完整回答
反对 回复 2023-09-22
  • 1 回答
  • 0 关注
  • 90 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号