i face this problem last time but i don't remember exectly but i think i follow this steps if i'm not wrong
Sorting the results by category, so forums belonging to the same category appear consecutively.
Tracking the current category title, so that a new <div class=''forum''> block is only opened when the category changes.
Appending forum rows inside the same table until a new category is detected.
Closing the previous table block when a new category starts or at the end of the loop.