I tried to understand your logic but failed... Maybe it's my problem, of course.
But in any case, did you hear about MVC (Model-View-Controller)? It means that it's better to separate the part where you get your data from the presentation part.
In this case it would be better not to use 'echo' inside the 'while' loop. Just get data, create arrays with data and then print them. It also will be more convenient to debug.
Another thing, can be even more important... It seems, that you may aggregate all information in one SELECT and then just take this info. Check for GROUP_CONCAT in the MySQL help.