【发布时间】:2014-11-12 12:30:16
【问题描述】:
最近我有一些将 mysql 查询结果转换为 json 用于测验系统的经验。查询结果包含一组问题和相关的答案。实现的过程旨在将这些问题和答案放入多维数组中,然后将其转换为 json 以构建测验数据库。我已经准备好使用适用于下面提到的 JSON 结构的 JS 程序(测验模块)。但是为了构建这个结构,我坚持使用以下 php 程序:
PHP 代码:
$query = "SELECT s1.question, s2.answers, s2.correct
FROM `questions` s1, `answers` s2
WHERE s1.id=s2.questionid AND s1.courseid=".$_POST['courseid']."";
$result = mysqli_query($mysqli, $query) or die ("<b>Select failed:</b> ".mysqli_error($mysqli));
$final_quiz = array();
$final_quiz['introduction'] = "Introduction text goes here";
while ($rows = mysqli_fetch_assoc($result_quiz)) {
$final_quiz['questions']['question'] = $rows['question'];
$final_quiz['questions']['question']['answers'] = array($rows['answers'], "correct"=> $rows['correct']);
}
// convert to JSON
$json = json_encode($final_quiz);
echo $json;
预期的 JSON 输出:
{
"introduction":"Some introductory text here",
"questions":[
{
"question":"Question number one here?",
"answers":["some incorrect answer", "a correct answer", "another incorrect answer"],
"correct":1}, // indicates an array key that is relates to keys in "answers"
...
]
}
如何组织多维数组以获得上述json结构?任何帮助将不胜感激。
更新
正确键中的值是答案键的索引,即如果我们有“正确”:1,则表示答案键的第二个值。来自 MySQL 的答案的正确值为 boolean (TRUE/FALSE)。因此,在将所有答案作为一组答案放入 answers_array_key 之前,应该记住为具有 TRUE 值的答案新分配的索引数组,将该索引数组作为值放入 correct_array_key 中。一个例子:
....
"answers":[0:"some incorrect answer", 1:"a correct answer", 2:"another incorrect answer"],
"correct":1}, // this is correct answer key
....
希望这将解释上述所需 json 结构的想法。
【问题讨论】:
标签: php arrays json multidimensional-array mysqli