如何在 PHP 中自定义 json_encode 数据?

问题描述

我有一个名为 questionsMysqL 数据库表,其中包含以下列:

id,question,category,type,difficulty,correct_answer,incorrect_answer_1,incorrect_answer_2,incorrect_answer_3

我需要将此表中的数据输出JSON 格式,但仅采用以下特定格式(例如错误答案拼凑在一起):

{
  "response_code": 0,"results": [
    {
      "category": "Science & Nature","type": "multiple","difficulty": "hard","question": "An organic compound is considered an alcohol if it has what functional group?","correct_answer": "Hydroxyl","incorrect_answers": [
        "Carbonyl","Alkyl","Aldehyde"
      ]
    },{
      "category": "Entertainment: Video Games","difficulty": "easy","question": "Which of the following is not a faction in Tom Clancy's The Division?","correct_answer": "CDC","incorrect_answers": [
        "Cleaners","Last Man Batallion","Rikers"
      ]
    },"difficulty": "medium","question": "Which of the following Call of Duty games was a ps3 launch title?","correct_answer": "Call of Duty 3","incorrect_answers": [
        "Call of Duty 4: Modern Warfare","Call of Duty: World at War","Call of Duty: Roads to Victory"
      ]
    }
  ]
}

有了PHPjson_encode的基础知识,我可以将数据以JSON格式输出,但无法以上述格式输出。我的 PHP 代码是:

$MysqLi = new MysqLi("localhost","root","","demo_db");
$statement = $MysqLi->prepare("SELECT * FROM questions limit 50");
$statement->execute(); 
$result = $statement->get_result();
$outp = $result->fetch_all(MysqLI_ASSOC);
echo json_encode($outp); // Tried this,but it's not outputting in desired format

//echo json_encode(($result->fetch_assoc())); // Tried this,but it's also not outputting in desired format
//echo json_encode(($result->fetch_array())); // Tried this,but it's also not outputting in desired format

我尝试了三种不同的方法来使用 json_encode,但我无法创建所需的格式,尤其是将错误答案设为类似嵌套数组的格式。

我该怎么办?

解决方法

您想要的输出中有字段,结果中没有返回这些字段,因此您必须自己构建。

这只是一个指导性的答案! 这不会产生完整的输出!您必须自己处理详细信息,尤其是对于 incorrect_answers .

$results = [
    'response_code' => 0,'results' => []
];

foreach($outp as $item) {
    $results['results'][] = $item;
}

echo json_encode($results,JSON_PRETTY_PRINT);
,

基本上,您希望一次检索一个结果集中的行(例如在 while 循环中),然后将检索到的行转换为您想要的格式并将其添加到 {{ 1}} 变量。

output