1

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';
7
  • Why are you creating a new array? Just encode $check_list. Commented Jan 4, 2016 at 19:30
  • That's a good point. I'll change that. Commented 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 ? Commented 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. Commented Jan 4, 2016 at 19:38
  • I'll update my post with my validation which fails with the string Commented Jan 4, 2016 at 19:39

2 Answers 2

1
$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
}
Sign up to request clarification or add additional context in comments.

1 Comment

You are a genius! Thank you so much!
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.