Reputation: 115
I am coding a PHP function, and I would like to ask a question. I have a problem with exploding a string in a particular way. I have tried to explain as well as I can down below.
What is this?
Well.. I am working on a solution to decrease the number of tables on my website. I can turn the table for admin rights into one field in the user table. However, I will then need to explode the text field into an array when loading the website. The code is looking like:
<?php
$string = "server1=(ban=(perm=false,normal=true),edit=true,delete=false),adminlog=true,server2=(ban=(perm=false,normal=true),edit=false,delete=true)";
function parseRights( $s="" ){
$context = array();
// code here
}
print_r(parseRights($string));
?>
Basically, I would want the result to be:
Array
(
[server1] => Array
(
[ban] => Array
(
[perm] => false
[normal] => true
)
[edit] => true
[delete] => false
)
[adminlog] => true
[server2] => Array
(
[ban] => Array
(
[perm] => false
[normal] => false
)
[edit] => false
[delete] => true
)
)
True and false should be PHP true and false. If written out like that, I know it will show 1 where true are, and nothing where 0 are.. but it's just to show you what I would like the array to look like after run through the function. I would like it to be able to create an "infinite" array, with each new parentheses creating a new array. Of cource I would gladly accept other ways to distinguish the correct rights if the function would work in the same manner.
Upvotes: 1
Views: 97
Reputation: 78994
Just to help you along a little. Better would be to have related tables that store each functional piece, such as a ban table and permission table both related to the servers table or something similar. If you're not going to store this properly in the database, at least save some trouble:
$array = array('server1'=>array('ban'=>array('perm'=>false,'normal'=>true),'edit'=>true,'delete'=>false));
$string = json_encode($array);
echo $string;
/*
{"server1":{"ban":{"perm":false,"normal":true},"edit":true,"delete":false}}
*/
$new_array = json_decode($string, true);
var_export($new_array);
/*
array
(
'server1' =>
array (
'ban' =>
array (
'perm' => false,
'normal' => true,
),
'edit' => true,
'delete' => false,
),
)
*/
See how the JSON string looks eerily similar to your string? You could also use serialize()
but JSON is standardized and portable.
Also, var_dump()
and var_export()
will show that true
and false
are actually stored, print_r()
just doesn't display the proper type.
Upvotes: 1