2

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
)

2 Answers 2

1

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

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

I think this fix problem

Sign up to request clarification or add additional context in comments.

Comments

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
)

3 Comments

thanks for pointing out the typo; I typed too fast and have amended.
yep. working with the answer from user3146300 - it was the option that needed to be set to force it to convert to an associative array in the json_decode
okay good. i tested both the casting and setting the second param to true and both worked fine with my code. anyway good if u've answer.

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.