[eluser]oddman[/eluser]
Any sort of application logic should NOT be in ANY view. Retrieving data to be stored in a variable is application logic, retrieved from the model. Inparo and Sean Murphy are right - this should all be done with one query, and the way you could do that would be to grab all categories for a particular parent, then create a tree with the various links, so that each parent_id has it's own array. Then you'd just loop through the entire tree, and for each element within a parent, see if it also has children (by doing something like if ($categories[$parent_id]).etc.