You'd probably find way better performance if you just did it all in one SQL query, instead of nested PHP loops.