Chris
Chris

Reputation: 1654

Convert array to JSON in proper format

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

Upvotes: 1

Views: 50

Answers (2)

jbrahy
jbrahy

Reputation: 4415

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

Upvotes: 0

Sammitch
Sammitch

Reputation: 32232

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

Upvotes: 1

Related Questions