我有两个由 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);
这让我得到了想要的结果,但解决方案远非有效。
任何有关这样做的更好方法的建议将不胜感激。建议可能包括更有效的方法:
- 通过改进 MySQL 查询来完成一些工作。
- php中的数组操作
- 通过在客户端操作(Javascript、jQuery 或 Underscore 便捷方法)获得所需的结果
谢谢