【发布时间】:2017-06-18 18:24:47
【问题描述】:
我需要从两个 MySQL 表创建一个多维 JSON。我的代码有效,但我认为它写得非常糟糕,因为它首先连接 DB 值,然后在 PHP 中分解结果字符串。必须有更好(更快)的方法来做到这一点。
我知道类似的问题已经被问过很多次,但我是个菜鸟,我不知道如何将答案应用到我的案例中。
所以,我有以下 MySQL 表:
tbl1
-----------------------------
id| question |correctanswer
-----------------------------
1|'Yes or no?'| 'Yes'
2| 'Who?' | 'Peter'
tbl2
-----------------------------
id|questionid| answeroptions
-----------------------------
1 | 1|'Yes'
2 | 1|'No'
3 | 2|'Peter'
4 | 2|'John'
5 | 2|'James'
6 | 2|'Jack'
我想构建这样的 JSON 字符串:
{
"id":"1",
"question":"Yes or no?",
"correct_answer":"Yes",
"answeroptions":[
"Yes",
"No"
]
}
{
"id":"2",
"question":"Who?",
"correct_answer":"Peter",
"answeroptions":[
"Peter",
"John",
"James",
"Jack"
]
}
这是我的代码:
$sql = "SELECT tabl1.id, tabl1.question, tabl1.correctanswer,
GROUP_CONCAT(DISTINCT tbl2.answeroptions)
FROM tabl1
LEFT JOIN tbl2 ON (tabl1.id = tbl2.questionid)
GROUP BY tabl1.id;";
$jsonarray = array();
$result = $conn->query($sql);
$i = 0;
while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
$jsonarray[$i]["topic"] = $row[0];
$jsonarray[$i]["id"]=$row[1];
$jsonarray[$i]["question"]=$row[2];
$jsonarray[$i]["correct_answer"]=$row[3];
$jsonarray[$i]["answeroptions"] = array();
$jsonarray[$i]["answeroptions"] = explode(",",$row[4]);
$i++;
}
for ($d=0; $d<count($jsonarray);$d++){
echo json_encode($jsonarray[$d])."<br>";
}
更新: 我对三个用例进行了性能测试:
- 布莱克的建议
- ded 的建议
- 将 answeroptions 合并到 tbl1 中的新列中以消除第二个请求,并使用 ded 的脚本进行了相应修改。
我用了一个 for 循环 * 100 次,结果如下:
- 0.16780591011047 秒
- 0.0067291259765625 秒
- 0.0005500316619873 秒
因此,基于性能,我得出结论,在 DB 中使用一对多关系并不总是最佳选择。对于这样简单的任务,所有数据都可以存储在同一个表中。
谢谢大家的帮助!
【问题讨论】:
-
我认为您只需要在代码末尾删除您的 for 循环即可。有
echo json_encode($jsonarray[$d]);就行了,别循环了 -
@bassxzero 感谢您的建议!仅针对可能也对此进行研究的其他人:我需要删除 [$d],它起作用了:
json_encode($jsonarray);. -
没注意到 d,但是它需要去
标签: php mysql json multidimensional-array one-to-many