I didn't studied it before, but now I can see, it is probably wrong.
You have two loops, second nested in first. But first loop goes through privileges for your user, and second goes through all privileges, so you have as many combination as there is privileges and privileges for your user.
I think, that you should do it as two not nested loops. First loop will read privileges for your user. And will store them into an array.
Second loop will go through all privileges, and will check them in the array. When it is in the array then it should be checked, when it is not in the array it should be unchecked.
Makes sense ?
Zdenek