PHP - how to parse a string of information into a useful form from a database
I am working on a web application system that has multiple applications, each with a primary key to identify them. Each user also has a security level associated with the application, for example application # 1 with security level 5. I want to store all the application / security information in the database as a token and then get that information to save it to the session.
So, given the following applications:
- Task application
- Email Application
- App Notes
and a user who has security levels 3, 5 and 7, respectively, the token will be saved as:
1.3|2.5|3.7.
My question is how to get this data in a convenient form? I thought to have it in an array with the key of the app id array, for example somearray[1] = 3
, somearray[2] = 5
etc., but I have no idea how to deal with this.
I am at the beginning of development on this side, so I have a very open view of the proposals. Thanks in advance for your help.
source to share
the token will be saved as:
1.3 | 2.5 |. 3.7
Why don't you store security levels in the database? It will be much easier to manage. I could imagine several tables, for example:
App
--------
id
name
....
Users
--------
id
name
email
...
App_users_permissions
--------
id
app_id (references App.id)
user_id (references Users.id)
level
Then you can make a simple request like:
SELECT level FROM App_users_permissions WHERE user_id = 1 AND app_id = 2
This request will then return the current Prior Activity ID for a specific App ID and User ID.
I think this would be the easiest way to handle this.
source to share
You should really redesign your database as suggested by Pierre-Olivier Bourgeois .
If you want to stick to the format described, you can use preg_match_all()
:
$subject = '1.3|2.5|3.7.';
$pattern = '=(\d+)\.(\d+)=';
$result = preg_match_all($pattern, $subject, $subpattern, PREG_SET_ORDER);
foreach ($subpattern as $match) {
$out[$match[1]] = $match[2];
}
print_r($out);
source to share
you really want to store this as one line (you shouldn't), you can use explode () to split it up one more time.
anyway, a much better solution would be to normalize your database correctly ( step by step for that ).
source to share