これはあなたの元の質問に対する回答ではありませんが、これが私のプロジェクトだった場合に使用するコメントを入れ子にするための迅速で汚いアプローチを示したいと思います。ほとんどの場合、より洗練された方法があり、ここには他のメンバーが提案しているかもしれません。
<?php
// Retrieve ALL comments related to this subject (including all replies and nested comments)
$rs = mysql_query('SELECT * FROM `comments` WHERE subjectid = '7' ORDER BY timecreated ASC');
// Process ALL comments and place them into an array based on their parent id
// Thus we end up with something like:
// $data[ 0 ][ 0 ] = array('commentid' => 1, 'subjectid' => 7, 'userid' => 1, 'timecreated' => '2012-05-01 12:00:00', 'parentid' => 0);
// $data[ 0 ][ 1 ] = array('commentid' => 2, 'subjectid' => 7, 'userid' => 5, 'timecreated' => '2012-05-01 14:00:00', 'parentid' => 0);
// $data[ 2 ][ 0 ] = array('commentid' => 3, 'subjectid' => 7, 'userid' => 1, 'timecreated' => '2012-05-01 16:00:00', 'parentid' => 2); This is a reply to commentid #2
// $data[ 2 ][ 1 ] = array('commentid' => 4, 'subjectid' => 7, 'userid' => 5, 'timecreated' => '2012-05-01 16:30:00', 'parentid' => 2); This is another reply to commentid #2
// $data[ 3 ][ 0 ] = array('commentid' => 5, 'subjectid' => 7, 'userid' => 3, 'timecreated' => '2012-05-01 17:00:00', 'parentid' => 3); This is a reply to the reply with commentid #3
while ($row = mysql_fetch_assoc($rs)){
$data[ $row['parentid'] ][] = $row;
}
function output_comments(&$data_array, $parentid){
// Loop through all comments with matching $parentid
foreach ($data_array[ $parentid ] as $k=>$v){
// Output all comments, open .comment DIV but do not close (for nesting purposes)
echo '<div class="comment"><strong>' . $v['username'] . ':</strong> ' . $v['message'];
// If there are any replies to this comment, output them by recursively calling this function
if (count($data_array[ $v['commentid'] ] > 0){
output_comments($data_array, $v['commentid']);
}
// Close the open DIV
echo '</div>';
}
}
// Call the output_comments() function, which will recursively run to support unlimited nesting
output_comments($data, 0);
あなたは、スタイルを使用して、ネストされたコメントのループ内でループを行うだろう親DIV.comment
<style type="text/css">
.comment .comment {
padding-left: 30px;
}
</style>
を持つ任意のDIV.commentをインデントによってかなり単純にコメントを入れ子になっただろうか?または、それらが1つのクエリから表示されるようにする方法がありますか? – user1260310
私の場合は、1つのMySQLステートメント内のすべてのデータを取得し、いくつかのPHPロジックとループを使用してネストします。ループ内でループを実行できますが、ネストされた応答の深さを制限するか、深くネストされたコメントをサポートするために十数個のループを作成しています。 IE:あなたがコメントをしたときにあなたのコメントに返信し、別の訪問者がその返信に返信し、別の訪問者がその返信に返信しました。私たちはすでに4つのループ、つまり4つのループです。あなたの実装でおそらくそれを深める可能性は低いですが、その可能性を制限したいのですか?考慮すべき何か。 –