I don't program php, yet a quick review of your code suggests that your problem is in the SQL.
Inner joins return multiple copies of the desired cells, since they denormalize the data.
You may discover that rewriting your SQL will effectively resolve your problem.
I recommend that you REFRAIN from resolving it in your php script; though effective, it is an abuse of server resources and should be crunched by your RDBMS.
Hope it helps...