简体   繁体   English

使用PHP将MySQL表转换为具有子数组的JSON数组

[英]mySQL table to JSON array with subarrays using PHP

I am currently reading data from a mySQL table in Javascript using PHP's json_encode. 我目前正在使用PHP的json_encode从Javascript中的mySQL表读取数据。 My table has this format: 我的表格具有以下格式: 在此处输入图片说明

And this structure: 而这个结构: 在此处输入图片说明

I am using this PHP code to put the into JSON form: 我正在使用以下PHP代码将JSON格式放入:

$sql = "SELECT `choice`, `choice_id`, `is_right_choice` FROM Question_choices WHERE `question_id` = 1";
$result = $conn->query($sql);
$rows = array();

if ($result->num_rows > 0) {
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}} 
else {
echo "Congrats, You Have Displayed All the Answers!";
}

header('Content-Type: application/json');
print json_encode($rows);

When I call this script, I get this result: 当我调用此脚本时,会得到以下结果:

[{"choice":"A","choice_id":"1","is_right_choice":"0"},
{"choice":"B","choice_id":"2","is_right_choice":"0"},
{"choice":"Correct","choice_id":"3","is_right_choice":"1"},
{"choice":"D","choice_id":"4","is_right_choice":"0"}]

However, I want to format my JSON so that it has an array of 'question_id' and if you call 'question_id[0] (or 1)', it will have a sub-array in it of all the 'choice' values that also have a 'question_id' of 1. 但是,我想格式化我的JSON,以便它具有一个'question_id'数组,如果您调用'question_id [0](或1)',它将在其中包含一个所有'choice'值的子数组。也有一个'question_id'为1。

Ignore the FROM Question_choices WHERE question_id = 1"; , that is just there to get a correct JSON call right now. In the future, my table will have many different values for 'question_id'. 忽略FROM Question_choices WHERE question_id = 1";这只是为了立即获取正确的JSON调用。将来,我的表将为'question_id'提供许多不同的值。

In short, I want to hopefully use PHP's JSON encode to format my JSON like this JSON: {question_id:1{{choice:A},{choice:B}}, question_id:2{{choice:C},{choice:D}}, etc...} 简而言之,我希望希望使用PHP的JSON编码将JSON格式设置为以下JSON:{question_id:1 {{choice:A},{choice:B}},question_id:2 {{choice:C},{choice: D}},等等...}

Is this possible using PHP or do I have to look elsewhere? 使用PHP可以做到这一点吗?还是我必须去别处看看?

This will group the choices together for each choice_id : 这会将每个choice_id的选择分组在一起:

SELECT GROUP_CONCAT( `choice` ), `choice_id`, `is_right_choice`
FROM Question_choices
GROUP BY `choice`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM