我在我的網站上有一個簡單的問答部分,允許評論。我目前使用循環和$ _GET ['id']值填充答案。這裏是我的查詢通過MySQL循環左加入PHP與2個單獨的查詢
<?php
try{
$parent=$_GET['id'];
$post_type = "2";
$stmt = $dbh->prepare(
"SELECT p.post_id, p.content, p.author, p.created, pc.comment_id AS comment_id, pc.content AS comment_content
FROM posts AS p
LEFT JOIN posts_comments AS pc
ON p.post_id = pc.parent_id
WHERE p.post_type = :post_type AND p.parent = :parent ");
$stmt->bindParam(':parent', $parent, PDO::PARAM_INT);
$stmt->bindParam(':post_type', $post_type, PDO::PARAM_INT);
$stmt->execute();
$answers_array = array();
while ($answers = $stmt->fetch(PDO::FETCH_ASSOC)) {
$answers_array[]= $answers;
}
}
?>
這返回數組
Array (
[0] => Array (
[post_id] => 12
[content] => I have an answer
[author] => Author1
[created] => 2012-06-09 21:43:56
[comment_id] =>
[comment_content] =>)
[1] => Array (
[post_id] => 13
[content] => My second answer
[author] => Author1
[created] => 2012-06-10 06:30:58
[comment_id] => 35
[comment_content] => 1st comment)
[2] => Array (
[post_id] => 13
[content] => My second answer
[author] => Author2
[created] => 2012-06-10 06:30:58
[comment_id] => 36
[comment_content] => 2nd comment)
[3] => Array (
[post_id] => 13
[content] => My second answer
[author] => Author2
[created] => 2012-06-10 06:30:58
[comment_id] => 37
[comment_content] => 3rd comment)
)
在我question.php頁我知道我會需要遍歷這些結果與類似
<?php $answer_count = count($answers_array);
for($x = 0; $x < $answer_count; $x++) {
$answers = $answers_array[$x];
}
?>
以下結果
我的問題 -
我不知道是否使用兩個單獨的查詢來拉t他評論與每個答案相關聯或使用我上面的連接並使用php構建另一個數組。我不知道如何誠實地做到這一點。如果我使用連接,我想要一個看起來像這樣的數組,但我不知道如何使用php中的循環來構建它。
Array (
[0] => Array (
[post_id] => 12
[content] => I have an answer
[author] => Author1
[created] => 2012-06-09 21:43:56
[comment_id] =>
[comment_content] =>)
[1] => Array (
[post_id] => 13
[content] => My second answer
[author] => Author1
[created] => 2012-06-10 06:30:58
Array(
[1] => Array (
[comment_id] => 35
[comment_content] => 1st comment)
[2] => Array (
[comment_id] => 36
[comment_content] => 2nd comment)
[3] => Array (
[comment_id] => 37
[comment_content] => 3rd comment))
一旦我有呀,我想我可以做一個對每個question.php頁面上我原來的PHP循環中的數組。
它可以幫助更多的來發表您的架構片段比它確實發佈了大量的示例輸出。 –
我縮短了輸出。我不確定需要多少才能回答這個問題。我會努力將模式放在問題中而不是輸出 – FajitaNachos