Recently I had some experience with converting mysql query results into json for a quiz system. Query results contain set of questions and related anwsers to them. The implemented procedure aims to put those questions and answers into multidimensional array and then convert it into json to build quiz db. I've ready to use JS procedure (quiz module) that works with below mentioned JSON structure. But to build this structure I'm stuck with the following php procedure:
Code in 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;
Expected JSON Output:
{
"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"
...
]
}
How to organize multidimensional array in order to get above mentioned json structure? Any help would be appreciated.
UPDATES
The values in correct keys are indexes of the answers keys, i.e. if we have "correct":1 that would mean second value of answers key. Correct values for answers that come from MySQL are boolean (TRUE/FALSE). So, before putting all answers in answers_array_key as a set of answers one should remember newly assigned index array for the answer with TRUE value put that index array in correct_array_key as value. An example:
....
"answers":[0:"some incorrect answer", 1:"a correct answer", 2:"another incorrect answer"],
"correct":1}, // this is correct answer key
....
Hope that will that will explain the idea of desired json sturcture mentioned above.