I'm currently making a mcq for a medical application and i want to make a Json from my database by a php but it's isn't working, someone advice me to Having a JSONObject for the question and a JSONArray for the Choices but i'm not able to make this and i don't understand why ! I followed a lot a tutorial but i can't figure out why i can't make this JSON :
{ //This is the JSON i want to make !
"QCM": {
"question": "Est-ce que Captain America gagne contre IronMan",
"id": "31",
"choix": ["Oui", "Non"]
}
}
But i can't, currently my PHP code is :
$db = mysqli_connect($host,$user,$pass,$db);
$questions = $db->query("SELECT question, id FROM question ORDER BY rand() LIMIT 1");
while($row = mysqli_fetch_assoc($questions)){
$id=$row['id'];
$QCM[] = $row;
$choix = $db->query("SELECT choix FROM choix WHERE id_question = $id ORDER BY rand()");
while ($row = mysqli_fetch_assoc($choix)) {
$QCM[] = $row;
}
}
echo json_encode(array("QCM"=>$QCM));
and there is the JSON i can get with this code :
{ //I don't want this JSON because i can't read the "choix" in my application
"QCM": [{
"question": "Est-ce que Batman gagne contre Superman",
"id": "30"
}, {
"choix": "Oui"
}, {
"choix": "Non"
}]
}
I hope someone can help me because i can't make the right json !
Here is my JAVA :
try
{
JSONArray QCM = response.getJSONArray("QCM");
for (int i=0; i<QCM.length(); i++) {
JSONObject getQcmObject = QCM.getJSONObject(i);
String questionGet = getQcmObject.getString("question");
symptomesQuestions.setText(questionGet);
JSONArray CHOIX = response.getJSONArray("choix");
for (int x =0; x<CHOIX.length(); x++){
JSONObject getChoixObject = CHOIX.getJSONObject(x);
String choiceGet = getChoixObject.getString("choix")
lesChoixButton.setText(choiceGet);
}
}
PHP structure required to create the example JSON
$jsonPhp =
(object) (array(
'QCM' =>
(object) (array(
'question' => 'Est-ce que Captain America gagne contre IronMan',
'id' => '31',
'choix' =>
array (
0 => 'Oui',
1 => 'Non',
),
)),
));
Online tool to compare JSON structures for differences...
As print_r:
stdClass Object
(
[QCM] => stdClass Object
(
[question] => Est-ce que Captain America gagne contre IronMan
[id] => 31
[choix] => Array
(
[0] => Oui
[1] => Non
)
)
)