I can't really tell you how to do this.
I can advise you to avoid using nested loops, as you could never get them to dynamically nest the amount you want.
I can advise you to put them all in one loop, and to maybe pass through the variables that will allow you to display them differently; what I mean is to try using php for all of the logic.. not the template.
I hope this helps. I can't really go any further as this is a generic php problem, it's up to you how you deal with it.
Regards,
Kelvin