TH1981
TH1981

Reputation: 3193

json object to array not referencing values

I'm doing something stupid and can't figure it out.

I'm pulling setting details stored in a mysql database as a json object and then converting them to an array.

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

I can print_r() this to the following:

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

Good so far.

If I try to update one of the settings, so for example changing 1 to equal 0, I get this:

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

I'm doing this simply with this:

$settings[1] = 0;

Ultimately I'm trying to unset the value if it's a 0 and then update the database. Instead of updating the value, it's creating a new entry and using unset doesn't do anything.

What am I doing wrong??

full code snippet for reference:

$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);

returns:

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

Upvotes: 2

Views: 53

Answers (2)

geoffreybans
geoffreybans

Reputation: 44

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
)

Upvotes: 0

BGH
BGH

Reputation: 56

Hi can you add secent param true to function json_decode like that :

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

I think this fix problem

Upvotes: 1

Related Questions