Chris Chris - 5 years ago 117
PHP Question

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

Answer Source
$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
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download