0
我有两个与topic_id相关的表(讲义和主题)。我需要作为他们相关主题的孩子参加讲座。所需json_encode($结果)应该是:将MySQL一对多结果集转换为JSON
[
{"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的或下划线方便的方法)
由于
你能告诉我这两张表(主题,讲座)的表结构吗? – Kabir 2013-03-06 11:25:17