json对象到数组不引用值

时间:2015-04-28 23:12:19

标签: php arrays

我做了一些愚蠢的事情,无法弄明白。

我将存储在mysql数据库中的设置细节作为json对象,然后将它们转换为数组。

$settings = (array)json_decode($user['settings']);

我可以print_r()以下内容:

Array
(
    [2] => 1
    [1] => 1
)

到目前为止很好。

如果我尝试更新其中一个设置,例如将1更改为等于0,我会得到:

Array
(
    [2] => 1
    [1] => 1
    [1] => 0
)

我只是这样做:

$settings[1] = 0;

最终我试图取消该值,如果它是0然后更新数据库。它不是更新值,而是创建一个新条目,使用unset不会做任何事情。

我做错了什么?

完整的代码段供参考:

$settings = (array)json_decode($user['settings']);
print_r($settings);

if(isset($form['usr'][$user['id_user']])){
    $settings[1] = 1;
}else{
    $settings[1] = 0;
    unset($settings[1]);
}

print_r($settings);

返回:

Array
(
    [2] => 1
    [1] => 1
)
Array
(
    [2] => 1
    [1] => 1
    [1] => 0
)

2 个答案:

答案 0 :(得分:1)

您可以将secent param true添加到函数json_decode中,如下所示:

$settings = json_decode($user['settings'], true); 

我认为这个修复问题

答案 1 :(得分:0)

For one, I see a syntax error in your code. Is it a typing error or it is part of the actual code you did run? This line to unset ->

unset($settings[1];)

The statement termination ";" should be outside as this

unset($settings[1]);

Here is what I have tried. Assuming the $user['settings'] is formed this way

$user['settings'] = array('2' => 1, '1' => 1);

And was turned to json object in this manner

json_encode($user['settings']);

Then the following code should work

$settings = (array)json_decode($user['settings']);
print_r($settings);

if(... true)
{
   $settings[1] = 1;
}
else
{
    $settings[1] = 0;
    unset($settings[1]);
}

print_r($settings);

Should output

Array
(
   [2] => 1
   [1] => 0
)

and

Array
(
    [2] => 1
)