亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

讀取文本文件后創建 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 關注
  • 103 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號