Some time ago I asked a question about nested loops on SO and as it was, there were queries inside the loops of my example and I got a clear answer:
NEVER EVER NEVER put an SQL query inside a loop
I've tried ever since and mostly it works. Just need to make an effort and write a query that retrieves all you need at once.
BUT what do you do when you have a dataset from a JOIN query which contains nested data which you need to output in a nested way?
Example join from table A and B:
A.a | B.a | B.b
--------|----------|-------------
fruits | banana | yellow
fruits | apple | red
animals | zebra | black&white
animals | elefant | gray
animals | fox | red
planets | earth | blue
planets | mars | red
ok, now I got that all in an array or rowset and now I need to display something like that:
fruits
- yellow banana
- red apple
animals
- black&white zebra
- gray elefant
- red fox
planets
- blue earth
- red mars
it seems obvious that it should work but I've tried to wrap my mind around it several times now and I just can't come up with a solution.
At the moment I do it my old way:
query groups foreach groups { query animals in group foreach animal }
but hey, NEVER EVER NEVER put sql inside a loop. so what shold I do? I do PHP but I think this is a meta question.