Depends on how your data is modeled. I dont know that, but I can assume that you use three relational tables. Something along these lines:
Post [parent] +-------------+---------+ | Field | Type | +-------------+---------+ | id | int | | value | varchar | +-------------+---------+ Comment [parent-child] +-------------+---------+ | Field | Type | +-------------+---------+ | id | int | | foreign_key | int | | value | varchar | +-------------+---------+ Comment->Comment [child] +-------------+---------+ | Field | Type | +-------------+---------+ | id | int | | foreign_key | int | | value | varchar | +-------------+---------+
You are looking to potentially run three queries. An easy fix would be to add a has_children field to each parent table. With that you would save a potential checkup and easily release some complexity in the PHP loop.
[parent-child] +--------------+---------+ | Field | Type | +--------------+---------+ | id | int | | foreign_key | int | | has_children | bool | <=== | value | varchar | +--------------+---------+
I can provide the PHP code if you like, but I'm assuming that you get the general idea.