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