我正在尝试在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));
答案 0 :(得分:0)
从您的代码中,可以像这样进行修改:
$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
答案 1 :(得分:0)
我在这里要做的是将“选择”放入数组中。希望有效。
$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));