Hmm. This is a tree structure. The total list has categories; each category has subcategories; each subcategory has final entries. Let's reflect that in how we store the data in PHP.
First, select all the stuff (including category, sub, final, etc) from the database.
For each row of the resultset (which I'll call $row): $tree[$row['category']][$row['sub']][$row['final']][] = $row
And that builds the tree.
Let's just see how that looks:
print_r($row);
You'll probably want them sorted. This almost certainly best done in SQL by adding an ORDER BY category,sub,final (or is that final,sub,category?) on the end, or in PHP with some nested loops running ksort() on each branch.
For display purposes you'll have some nested loops.
foreach($tree as $kcat=>$category)
{ ...Output category header stuff. The name of the category is in $kcat and the contents of the category is in $category.
foreach($category as $ksub=>$sub)
{ ... Output the subcategory stuff.
foreach($sub as $kfin=>$final)
{...Output the final stuff.
}}}