I'm building a form to do the following:
- Print a table of users and permissions, pulling from MySQL. Each permission a user has is a checked box, and each one they lack is an unchecked box.
- Allow an administrator to check and uncheck boxes to grant or remove permissions.
- When the form is submitted, show a confirmation page with ONLY the users whose permissions will be changed, highlighting the specific changes.
- When the changes are confirmed, modify the database accordingly.
To do this, I'm creating two arrays of user permissions: one according to what the database shows, and one according to what the form shows.
If a user lacks a permission in MySQL, it will be shown as a 0. If they lack a permission in the form submission, it simply won't exist.
Here are two simple examples of the arrays:
Database array
[User1] => Array ([public] => 1 [private] => 1 [secret] => 1 ) [User2] => Array ([public] => 1 [private] => 0 [secret] => 0 )
Form submission array (revoking "secret" from User1 and giving it to User2)
[User1] => Array ([public] => 1 [private] => 1 ) [User2] => Array ([public] => 1 [secret] => 1 )
Question
How can I elegantly combine these two arrays to make a "changes" array, such that:
- Users with identical permissions in both are omitted
- Remaining users have all permissions - public, private and secret - set to either 0 or 1.
- Each permission is 0 if it was missing from the form submission array, and 1 if it was in the form submission array
For example, combining the above would give:
[User1] => Array ([public] => 1 [private] => 1 [secret] => 0 ) [User2] => Array ([public] => 1 [private] => 0 [secret] => 1 )
Attempts so far
- As a first step, I have tried using array_merge() with the forms array listed second, thinking it would overwrite the database array where they differed. Instead, it deleted elements that differed.
- I have tried setting up a foreach() statement to compare the two arrays, but it's becoming complicated, and I think there must be a simpler way
UPDATE
Whew! A new answer drew my attention back to this old question. I got this working, but later I scrapped this crazy code - it was way too complicated to go back and work with. Instead, I wrote a PHP back end script to change one permission at a time, then wrote an AJAX front end to send changes over it. Much simpler code, and the changes are instantaneous for the user. A highlight effect gives instant, on-page feedback about what has changed.