私のウェブサイトには、コメントを許可する簡単な質問と回答のセクションがあります。現在、ループと$_GET['id']値を使用して回答を入力しています。これが私の質問です
<?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];
}
?>
私の質問 -
2つの別々のクエリを使用して各回答に関連付けられたコメントを取得するか、上記の結合を使用して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ループ内でそれぞれに対してを実行できると考えていました。