Your outermost loop lacks a sort clause.
I assume that you want an order like this, so that the thread with the youngest reply or topic creation timestamp is displayed first:
TOPIC 1 (timestamp 1)
REPLY 7 (timestamp 7)
TOPIC 3 (timestamp 3)
REPLY 4 (timestamp 4)
REPLY 5 (timestamp 5)
TOPIC 2 (timestamp 2)
It might be easier if you would not separate topics and replies in different tables but to pack all posts belonging to a thread into the same table - the first post, too.