in reply to Nested loops?

It is quite difficult to understand your code because we have no idea of the contents of $sql1 and $sql2.

It would be very useful if you provided sample input data for those, much in the way stevieb dit it in his answer.