PHP中JSON结构的多维数组

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.

You can try to use the php json_encode command. (link on php.net -> http://php.net/manual/it/function.json-encode.php)

The link show some example of array structure. On php.net it says it works with each type of structure (not resources).

Edit: as i see you already use this command, but how is the actual output? How much is different from your desired one?

Add one counter $i and try the below code:

        $i = 0;
        while ($rows = mysqli_fetch_assoc($result_quiz)) {
        $final_quiz['questions'][$i] = array(
            'question' => $rows['question'],
            //'answers' => $rows['answers'], UPDATE THIS LINE
            'answers' => array(
                              '1' => $rows['answers'][1], 
                              '2' => $rows['answers'][2], 
                              '3' => $rows['answers'][3]) 
            // Why I started from index one? if index is consecutive from 0 to n 
            // will remove the index in JSON, so start indexing from 1 and make some changes in ur code

            'correct' => $rows['correct']
        );
        $i++;
        }

this will work

I think this will produce the result you want.

while ($rows = mysqli_fetch_assoc($result_quiz)) {
    $final_quiz['questions'][]= array(
        'question' => $rows['question'],
        'answers' => array($rows['answers']), 
        'correct'=> $rows['correct']
    );
}

In your code, you are overwriting a single element of that array instead of appending the other questions

I believe this will solve it for you (I've used an array to test, I hope I got the question right).

You will need to change the foreach loop back to your while loop. I might have used a bit of different naming, you might need to change a thing or 2 to match your exact names:

<?php

$tmp = array (
    array("question"=> "this is a q", "answer"=>"incorrect", "correct" => false),
    array("question"=> "this is a q", "answer"=>"incorrect1", "correct" => false),
    array("question"=> "q1", "answer"=>"correct", "correct" => true),
    array("question"=> "q1", "answer"=>"incorrect", "correct" => false),
    array("question"=> "q1", "answer"=>"incorrect1", "correct" => false),
    array("question"=> "this is a q", "answer"=>"incorrect1", "correct" => false),
    array("question"=> "this is a q", "answer"=>"incorrect2", "correct" => false),
    array("question"=> "this is a q", "answer"=>"correct", "correct" => true),
    array("question"=> "this is a q", "answer"=>"incorrect3", "correct" => false)
);

$QAndA = array();
foreach ($tmp as $t){
    if (!isset($QAndA[$t['question']]['answers']))
        $QAndA[$t['question']]['answers'] = array();
    $QAndA[$t['question']]['answers'][] = $t['answer'];
    if ($t['correct'])
        $QAndA[$t['question']]['correct'] = count($QAndA[$t['question']]['answers']) -1;
}

foreach ($QAndA as $q => $data){
    $final_quiz['questions'][] = (object)array("question" => $q,
                                               "answers" => $data['answers'],
                                               "correct" => $data['correct']);

}
$json = json_encode($final_quiz);
echo $json;
?>

Result:

{
    "questions": [{
        "question": "this is a q",
        "answers": ["incorrect", "incorrect1", "incorrect1", "incorrect2", "correct", "incorrect3"],
        "correct": 4
    }, {
        "question": "q1",
        "answers": ["correct", "incorrect", "incorrect1"],
        "correct": 0
    }]
}

I do want to apologize for the naming conventions here and the somewhat brute attitude this code presents, but it is very late here;