Are you looping through all of table #1 or are you limited by some search query? Either way, you probably will be using some sort of while() or foreach() loop.
It looks like you want to run a second loop inside a first loop. This sounds very inefficient. Could you do a table join between the two tables? This would be more efficient and probably faster.