Muhammad Catubig Muhammad Catubig - 7 months ago 28
SQL Question

Multi-dimensional array to JSON

I am trying to print my data and encode it into JSON. I'm extracting the data from my MySQL database for a quiz. The data that I am trying to extract 1 question, 1 category and 4 options to make a set of quiz. I think I nearly got it how to make it work but I failed to find out how. This was the result check in this link.
Paste the JSON to this link so that you can easily format it. From that JSON data, I want to output like this for each question:

"What is the approximate number of islands that comprise the Philippines?",
"Philippine Geography",
[
{
"quiz_choice_id":"5",
"choice":"7000",
"is_correct_choice":"1"
},
{
"quiz_choice_id":"6",
"choice":"6000",
"is_correct_choice":"0"
},
{
"quiz_choice_id":"7",
"choice":"8000",
"is_correct_choice":"0"
},
{
"quiz_choice_id":"8",
"choice":"9000",
"is_correct_choice":"0"
}
],


This is my code for that:

<?php
/**
* Created by PhpStorm.
* User: Muhammad
* Date: 19/04/2016
* Time: 00:46
*/
require_once('Database_Connect.php');

$questions_query = "SELECT question, quiz_choice_id, choice ,is_correct_choice, category FROM category_question cq, question q, question_choices qc WHERE q.quiz_question_id = qc.quiz_question_id AND q.cat_ques_id = cq.cat_ques_id LIMIT 10";

$questions_query_result = mysqli_query($con, $questions_query) or die("error loading questions");

$questions_results = array();

encode_result($questions_query_result);

function encode_result($result)
{
//$response = array();
$questions = array();
//$choices = array();
while ($r = mysqli_fetch_array($result)) {
//$response[] = $r;
//$questions = array('question' => $r[0]);
$questions[] = $r['question'];
$questions[] = $r[4];
$choices[] = array('quiz_choice_id' => $r[1], 'choice' => $r[2], 'is_correct_choice' => $r[3]);
$questions[] = $choices;


//array_push($questions, $questions['question']);
//array_push($questions_results, $questions);
}
echo json_encode(array('questions'=>$questions));
}

mysqli_close($con);


The design of the database is this:
enter image description here

I can't find a way to make it work because from the database
quiz_choice_id,choice, is_correct_choice
are in a different table but I combined all into one table as you can see in my SQL statement
$questions_query
. Please let me know how can I fix this. Thanks in advance.

Answer

Do you want the json to look like this?

 [ {
  "question" : "What is the approximate number of islands that comprise the Philippines?",
  "category"    : "Philippine Geography",
  "choices" : [  
         {  
            "quiz_choice_id":"5",
            "choice":"7000",
            "is_correct_choice":"1"
         },
         {  
            "quiz_choice_id":"6",
            "choice":"6000",
            "is_correct_choice":"0"
         },
         {  
            "quiz_choice_id":"7",
            "choice":"8000",
            "is_correct_choice":"0"
         },
         {  
            "quiz_choice_id":"8",
            "choice":"9000",
            "is_correct_choice":"0"
         }
      ]
  },{
    ..... // next question
 }]

You'll have to do something like this, but I have no idea what the results of the query is.

    $questions = array();
    while ($r = mysqli_fetch_array($result)) {
        $key = $r['quiz_question_id']; // you need a key here that is unique to the question, so i think this will do looking at the schema you posted, this will group them in that segment of the array.
        if( !isset( $questions[$key] ) ){
            //if we never had this question, create the top level in the results
            $questions[$key] = array(
                'question' => $r['question'],
                'category'    => $r['category'],
                'choices'  => array()
            );
        }
        //add in the choices for this question
        //on the next iteration, the key is the same so we only do this part
        //and append that rows choices to the previous data using $key to match the question
        $questions[$key]['choices'][] = array('quiz_choice_id' => $r['quiz_choice_id'], 'choice' => $r['choice'], 'is_correct_choice' => $r['is_correct_choice']);
    }

Make sure to add quiz_question_id to your query if this is the questions id, unique identifier. Essentially this will group them together, as this will be the same for each row with that question's choices.

I added string keys to the output, I wouldn't mix using string keys and numbered index. I hope I mapped them out right.

Also I haven't tested this at all, so sorry if there are any syntax errors.