Well loading from SQL efficiently is the hard part.
You want to do this with only one query.
So say you have a comment table with `id`, `reply_to`, and `comment`. (just to keep it simple)
For comments that aren't replies, default the `reply_to` field as 0. (Make sure there are no ID's with a value of 0). Make one and ONLY one row with a blank value in the `comment` field. This row is to be eventually filtered out by whatever you display your data with.
Use this query:
Code:
SELECT `cmt1`.*, `cmt2`.`comment` as `reply`
FROM `comments` as `cmt1`,`comments` as `cmt2`
WHERE`cmt1`.`id` = `cmt2`.`reply_to` OR (`cmt1`.`reply_to` = 0 AND `cmt2`.`comment`="")
It should load all of the comments in order with their replies. Filter out the repeating comments, and just show the replies. Start the indent at 0.
Here's some rules for inside the loop you use the above query on:
1. If the indent is 0, show the comment AND the reply ONLY if there is a reply. (Otherwise just show the comment), log the reply and indent.
2. If the comment is equal to the previous reply then show the reply ONLY; continue to indent and to log the replies.
3. repeat step 2 as long as it takes..
4. If the comment is equal to a previous reply, but not the most recent, then adjust the indent to a smaller number accordingly. Example, if it's a reply to the first child comment, make the indent 2, for a second child comment. If it's a reply to a parent comment, make the indent 1, etc.
5. If the reply field is blank, display nothing. dispose of the log, set the indent to 0, repeat step 1.
Adjust them as you see fit, I haven't tested any of this except for the query itself.