Search code examples
phparraysjsonencode

How to encode multiple json elements using PHP?


I'm trying to create a questionnaire app in Android and I can already get the questions from the database and show it as JSON Array but it will be displayed in this format:

{
    "result": [
        {
            "id_question": "1",
            "question_name": "Grade level",
            "choices": "Grade 11, Grade 12"
        },
        {
            "id_question": "2",
            "question_name": "Expected grade in this subject",
            "choices": "90-100, 75-89, 60-74, Below 60"
        }
    ]
}

But the library I'm using in Android is only accepting this kind of JSON format for showing the questions:

{
  "survey_properties": {
    "intro_message": "To get a reliable result for the evaluation, please respond to all questions.",
    "end_message": "Your answers have been recorded. <br>Thank you for taking the time to answer the evaluation."
  },
  "questions": [
    {
      "id_question": "1",
      "question_name": "Grade Level",
      "choices": [
        "Grade 11",
        "Grade 12"
      ]
    },
    {
      "id_question": "2",
      "question_name": "Expected Grade in this subject",
      "choices": [
        "90-100",
        "75-89",
        "60-74",
        "Below 60"
      ]
    }
  ]
}

How can I achieve this kind of output in PHP? This is the script I'm using:

$query = "SELECT * FROM question_test";

$r = mysqli_query($conn, $query);
$result = array();

while($row = mysqli_fetch_array($r)) {
    array_push($result,array(
        "id_question"=>$row['id_question'],
        "question_name"=>$row['question_name'],
        "choices"=>$row['choices']
        )
    );
}

echo json_encode(array("result"=>$result));


Solution

  • From your code, it could be modified like this:

    $query = "SELECT * FROM question_test";
    
    $r = mysqli_query($conn, $query);
    $result = array();
    
    while ($row = mysqli_fetch_array($r)) {
        array_push($result,array(
            "id_question"=>$row['id_question'],
            "question_name"=>$row['question_name'],
            "choices"=>explode(', ', $row['choices'])
        ));
    }
    
    echo json_encode(array("result"=>$result));
    

    You have to add more information like survey_properties