我无法制作这个JSON

时间:2016-04-29 20:58:10

标签: php json

我目前正在为一个医疗应用程序制作一个mcq,我想通过php从我的数据库中创建一个Json,但是它还没有工作,有人建议我拥有一个JSONObject用于问题和选择的JSONArray,但我无法做到这一点,我不明白为什么!我跟着很多教程,但我无法弄清楚为什么我不能制作这个JSON:

{ //This is the JSON i want to make !
    "QCM": {
        "question": "Est-ce que Captain America gagne contre IronMan",
        "id": "31",
        "choix": ["Oui", "Non"]
    }
}

但我不能,目前我的PHP代码是:

$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));

并且我可以使用此代码获得JSON:

{ //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"
    }]
}

我希望有人可以帮助我,因为我无法做出正确的json!

这是我的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);
                                }
                            }

创建示例JSON

所需的PHP结构
$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
                )
        )
)

2 个答案:

答案 0 :(得分:1)

你有没有试过这样的事情:

<?php

$db         = mysqli_connect($host,$user,$pass,$db);
$counter    = 0;
$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()");

    $arrTemp= array();      // HERE A TEMPORAL ARRAY 
    while ($row2 = mysqli_fetch_assoc($choix)) {
        $arrTemp[] = $row2['choix'];
    }
    //TRY THIS:
    $QCM[$counter]["choix"]  = $arrTemp; //ADD THE TEMPORAL ARRAY TO THE $QCM ARRAY
    $counter++;
}
echo json_encode(array("QCM"=>$QCM));

我建议你在Java代码中尝试这个:

package com.company;

import org.json.JSONArray;
import org.json.JSONObject;


public class Main {

public static void main(String[] args) {
    String jsonExample      = "[{\"QCM\":{\"question\":\"Est-ce que Captain America gagne contre IronMan\",\"id\":\"31\",\"choix\":[\"Oui\",\"Non\"]}}, {\"QCM\":{\"question\":\"Do you know who the 1st President of the United States is?\",\"id\":\"32\",\"choix\":[\"Yes\",\"No\"]}}]";
    JSONArray jsonArray;
    try{
        jsonArray           = new JSONArray(jsonExample);

        for(int i = 0; i<jsonArray.length(); i++){
            JSONObject tempObject   = jsonArray.getJSONObject(i);
            JSONObject qcmObject    = tempObject.getJSONObject("QCM");
            String qcmQuestion      = qcmObject.getString("question");
            JSONArray qcmChoice     = qcmObject.getJSONArray("choix");
            //SET THE TEXT IN THE TEXT FIELD:
            ////symptomesQuestions.setText(qcmQuestion);

            //NOW LOOP THROUGH THE ARRAY OF CHOICES AND DO AS YOU WISH WITH THE CONTENT...
            for(int c=0; c<qcmChoice.length(); c++){
                //BECAUSE YOU MAY HAVE MORE THAN 1 CHOICES, YOU MAY HAVE TO CREATE YOUR BUTTONS DYNAMICALLY...
                //IF YOU SET THE BUTTON TEXT OF lesChoixButton TO ANY VALUE, SUBSEQUENT VALUES IN THE LOOP WILL OVERRIDE IT.
                //SO DYNAMICALLY CREATE YOUR BUTTONS....
                System.out.println( qcmChoice.get(c) + "\n");   // PRINTS Oui   Non...  AND THEN Yes    No  
                ////lesChoixButton.setText(qcmChoice.get(c));
            }

            System.out.print(qcmQuestion);
            System.out.print("\n\n");
            System.out.print(qcmChoice);
            System.out.print("\n\n");

        }
    }catch (Exception e){

    }
}
}

测试此代码:

package com.company;

    import org.json.JSONArray;
    import org.json.JSONObject;

    import javax.swing.*;
    import java.awt.*;


    public class Main extends JFrame{

        Main(String g){
            super(g);     
        }

        public static void main(String[] args) {
            String jsonExample      = "[{\"QCM\":{\"question\":\"Est-ce que Captain America gagne contre IronMan\",\"id\":\"31\",\"choix\":[\"Oui\",\"Non\"]}}, {\"QCM\":{\"question\":\"Do you know who the 1st President of the United States is?\",\"id\":\"32\",\"choix\":[\"Yes\",\"No\"]}}]";
            JSONArray jsonArray;
            try{
                jsonArray           = new JSONArray(jsonExample);
                Main fr             = new Main("QCM QUESTIONS");
                fr.setLayout(new GridLayout(10,10));
                final JPanel  tempPanel     = new JPanel();
                tempPanel.setLayout(new GridLayout(4,4));

                for(int i = 0; i<jsonArray.length(); i++){
                    JSONObject tempObject   = jsonArray.getJSONObject(i);
                    JSONObject qcmObject    = tempObject.getJSONObject("QCM");
                    String qcmQuestion      = qcmObject.getString("question");
                    JSONArray qcmChoice     = qcmObject.getJSONArray("choix");
                    JTextField  tempQuest   = new JTextField(20);
                    tempQuest.setText(qcmQuestion);
                    fr.add(tempQuest);

                    //SET THE TEXT IN THE TEXT FIELD:
                    ////symptomesQuestions.setText(qcmQuestion);

                    //NOW LOOP THROUGH THE ARRAY OF CHOICES AND DO AS YOU WISH WITH THE CONTENT...
                    for(int c=0; c<qcmChoice.length(); c++){
                        //BECAUSE YOU MAY HAVE MORE THAN 1 CHOICES, YOU MAY HAVE TO CREATE YOUR BUTTONS DYNAMICALLY...
                        //IF YOU SET THE BUTTON TEXT OF lesChoixButton TO ANY VALUE, SUBSEQUENT VALUES IN THE LOOP WILL OVERRIDE IT.
                        //SO DYNAMICALLY CREATE YOUR BUTTONS....
                        System.out.println( qcmChoice.get(c) + "\n");   // PRINTS Oui   Non...  AND THEN Yes    No
                        final JButton  tempBtn     = new JButton();
                        tempBtn.setAlignmentX(0);
                        tempBtn.setAlignmentY(20 + 20*c);
                        tempBtn.setSize(new Dimension(150, 30));

                        tempBtn.setText( (String)qcmChoice.get(c) );
                        fr.add(tempBtn);
                       //fr.add(tempBtn);
                        ////lesChoixButton.setText(qcmChoice.get(c));
                    }
                    final JLabel tempSpacer     = new JLabel( " " );
                    tempSpacer.setText( "  ");
                    fr.add(tempSpacer);

                    System.out.print(qcmQuestion);
                    System.out.print("\n\n");
                    System.out.print(qcmChoice);
                    System.out.print("\n\n");

                }

                fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                fr.setVisible(true);
                fr.setSize(300,300);
            }catch (Exception e){

            }
        }
    }

答案 1 :(得分:0)

只需创建自填充数据(在您的情况下,它是从数据库中填充的)。

$expected = [
    "QCM" => [
            "question" => "Est-ce que Captain America gagne contre IronMan",
            "id"       => "31",
            "choix"    => ["Oui", "Non"]
        ]
    ];

echo (json_encode($expected , JSON_PRETTY_PRINT));

结果:

enter image description here

从您的代码中猜测,可能是:

$QCM = [ 
    "question" => $row['question'],
     "id" => $row['id'], 
     "choix" => [$row['i dont know column name']
] 

提示:

“QCM”将是您的主数组键,同时question,id,choix是“QCM”中的数组键。您可以使用以下方法制作上面图像的json结构:

$expected = [
    "QCM" => [
            "question" => "Est-ce que Captain America gagne contre IronMan",
            "id"       => "31",
            "choix"    => ["Oui", "Non"]
        ]
    ];

等于:

$q['QCM']['question'] = 'Est-ce que Captain America gagne contre IronMan ';
$q['QCM']['id'] = 31;
$q['QCM']['choix'] = ['Oui', 'Non'];

就像@MarkB在评论时说的那样。