I'm trying to convert my array to JSON.
My JSON is stored in the database and will later be decoded for permission checking.
Example,
How I want it to be stored in the database:
{ "admin": 1,
"create_posts": 1,
"edit_posts": 1,
"delete_posts": 1 }
How it is being stored now:
{"0":"\"admin\": 1",
"1":"\"create_posts\": 1",
"2":"\"edit_posts\": 1",
"3":"\"delete_posts\": 1"}
My code:
$check_list = $_POST['check_list'];
$list = array();
foreach($check_list as $key) {
$key = '"' . $key .= '": 1';
array_push($list, $key);
}
$json = json_encode($list, JSON_FORCE_OBJECT);
How would I make it so that it stores in the database like I want it to be?
I'm quite new to this, so any hints instead of direct answers is also much appreciated!
UPDATE:
JSON decode and validation:
$permis = json_decode($permissions->permissions, true);
echo ($permis['admin'] == true) ? 'allowed' : 'disallowed';
-
Why are you creating a new array? Just encode $check_list.aynber– aynber2016年01月04日 19:30:17 +00:00Commented Jan 4, 2016 at 19:30
-
That's a good point. I'll change that.Chris– Chris2016年01月04日 19:30:40 +00:00Commented Jan 4, 2016 at 19:30
-
Why not just leave it like that, you said you need this for validation somewhere else. Most languages are capable of decoding this json string. Any particular language this failed for ?Marius Ilie– Marius Ilie2016年01月04日 19:36:12 +00:00Commented Jan 4, 2016 at 19:36
-
Because the foreach is not creating a proper array. The array would be [0] => "admin: 1", [1] => "create_posts: 1" .. i.e., the key/value pairs are strings inside the array.aynber– aynber2016年01月04日 19:38:41 +00:00Commented Jan 4, 2016 at 19:38
-
I'll update my post with my validation which fails with the stringChris– Chris2016年01月04日 19:39:01 +00:00Commented Jan 4, 2016 at 19:39
2 Answers 2
$arr = [ 'a', 'b', 'c' ];
echo json_encode(
array_combine(
$arr,
array_fill(0, count($arr), 1)
),
JSON_PRETTY_PRINT
);
Output:
{
"a": 1,
"b": 1,
"c": 1
}
1 Comment
I'm assuming the incoming data looks like this.
$incoming_data = "admin=1&create_posts=1&edit_posts=1&delete_posts=1";
$pairs = parse_str($incoming_data);
so we take the incoming pairs and use the $key as the array index so you don't get the extra array element index.
$permissions = array();
foreach($pairs as $key => $value){
$permissions[$key] = $value;
}
then we encode the new array to get the JSON you're looking for.
print json_encode($permissions);
will print out JSON like this:
{
"admin":"1",
"create_posts":"1",
"edit_posts":"1",
"delete_posts":"1"
}
The main thing to change in your code is this.
foreach($check_list as $key) {
$list[$key] = 1;
}