我有两个与topic_id相关的表格(讲座和主题)。我需要作为相关主题的孩子参加讲座。所需的json_encode($ result)应为:
[
{"id":"2","name":"topic 3",
"lectures": [
{"id":"9", "topic_id":"2","name":"lecture 1"},
{"id":"10","topic_id":"2","name":"lecture 2"},
{"id":"11","topic_id":"2","name":"lecture 3"}
]
},
{"id":"3","name":"topic 4",
"lectures": [
{"id":"12","topic_id":"3","name":"lecture 1"},
{"id":"13","topic_id":"3","name":"lecture 2"},
{"id":"14","topic_id":"3","name":"lecture 3"}
]
}
]
一种可能的解决方案是像这样重新生成数组
$topics = $db->query("select * FROM topic")->fetchAll(PDO::FETCH_ASSOC);
$lectures = $db->query("SELECT * FROM lecture")->fetchAll(PDO::FETCH_ASSOC);
foreach($topics AS $topic) {
$result[$topic["id"]] = $topic;
$result[$topic["id"]]["lectures"] = array();
}
foreach($lectures AS $lecture) {
$result[$lecture["topic_id"]]["lectures"][] = $lecture;
}
echo json_encode($result);
结果是:
[
{"2": {"id":"2","name":"topic 3",
"lectures": [
{"id":"9", "topic_id":"2","name":"lecture 1"},
{"id":"10","topic_id":"2","name":"lecture 2"},
{"id":"11","topic_id":"2","name":"lecture 3"}
]
},
{"3": {"id":"3","name":"topic 4",
"lectures": [
// ...
]
这仍然不是我们要求的。我需要删除最顶层的id(用作键)可以通过重新生成结果数组在服务器或客户端完成,只保留值。 (不那么优雅)的解决方案可能是:
$result2 = array();
foreach($result AS $res) {
$result2[] = $res;
}
echo json_encode($result2);
这让我获得了理想的结果,但解决方案效率很低。
任何有关更好的方法的建议都将受到赞赏。建议可能包括更有效的方式:
由于
答案 0 :(得分:0)
你的问题有点含糊,所以我猜这里。我认为你只需要一个MySQL声明。
SELECT lecture.id lid,lecture.name lname,topic.id tid,topid.name tname
FROM lecture
LEFT JOIN topic ON lecture.id = topic.id
ORDER BY lid,tid
您的结果应该是正确的顺序。