Take a look at this from David Powers
I have used it a number of times, just ensure you read it thoroughly so you get the result you want.
It doesn't give you exactly what you outlined, but is a neat solution
post_Create_nested_lists_from_a_recordset__PHP_-16720.html