使用PhP向json对象添加数组

时间:2018-04-12 06:48:54

标签: php json

我想在从数据库中检索问题时对一个问题的答案数组进行编码。

期望的结果:

[{"question":"What Barks","answers":["Cats","Dogs","Birds","Elephants"],"correct":1}]

源代码

require_once("connect.php");
$sql = "SELECT questions.question, GROUP_CONCAT(answers.answer) answers, questions.correct FROM questions,answers  where answers.questionID = questions.questionID group by questions.question";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    $data = array();
    while($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
}

echo json_encode($data);

mysqli_close($conn);

当前结果:

[{"question":"What Barks?","answers":"Cat,Dog,Fish,Cow","correct":"1"}]

2 个答案:

答案 0 :(得分:1)

更改mysql查询,如下所示:

> SELECT questions.question, 
> questions.correct,GROUP_CONCAT(answers.answer) answers FROM
> questions,answers  where answers.questionID = questions.questionID
> group by questions.question
  

这里我们使用MySQL的GROUP_CONCAT聚合函数

答案 1 :(得分:1)

以下是示例解决方案,基于您的问题中的示例:

require_once("connect.php");
$sql = 
    "SELECT questions.question, GROUP_CONCAT(answers.answer) answers, questions.correct FROM questions, answers WHERE answers.questionID = questions.questionID GROUP BY questions.question";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    $data = array();
    while($row = mysqli_fetch_assoc($result)) {
        $a = array(
            "question"=>$row["question"],
            "answers"=>explode(",", $row["answers"]),
            "correct"=>$row["correct"]
        );
        $data[] = $a;
    }
}
echo json_encode($data);
mysqli_close($conn);