【问题标题】:How to encode multiple json elements using PHP?如何使用 PHP 编码多个 json 元素?
【发布时间】:2017-09-19 07:25:23
【问题描述】:

我正在尝试在 Android 中创建一个问卷调查应用程序,我已经可以从数据库中获取问题并将其显示为 JSON 数组,但它将以这种格式显示:

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

但我在 Android 中使用的库只接受这种 JSON 格式来显示问题:

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

如何在 PHP 中实现这种输出?这是我正在使用的脚本:

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

【问题讨论】:

  • 循环遍历数组,将选项分解成数组等等瞧?
  • 谢谢!现在从您和@tuan-duong 的回答中得到了选择的解决方案。我现在的问题是如何将survey_properties 添加到数组中

标签: php arrays json encode


【解决方案1】:

根据您的代码,可以这样修改:

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

您必须添加更多信息,例如survey_properties

【讨论】:

  • 这成功了!谢谢! :) 我怎样才能添加survey_properties?我尝试array_push 数据,但我似乎无法获得与上述格式相同的survey_properties 输出。
【解决方案2】:

我在这里要做的是将“选择”放入一个数组中。希望有效。

$query = "SELECT * FROM question_test";

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

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

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

【讨论】:

  • 这显示了Parse error: syntax error, unexpected ';', expecting ',' or ')'
猜你喜欢
  • 1970-01-01
  • 2018-08-18
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
  • 2015-09-02
相关资源
最近更新 更多