How to change a php object’s value

Asked

Viewed 798 times

0

I’m passing an object created in a jQuery file to php and getting it from the following code.

$data = $_POST['data'];
$d = json_decode($data);
$user = $d->user;
$season = $d->season;
print_r($d);

What is returning to me the following:

stdClass Object
(
    [user] => 1
    [season] => 2016
    [week201548] => stdClass Object
        (
            [bloco] => Microciclo
            [day24112015] => stdClass Object
                (
                    [z1] => 0
                    [z2] => 0
                    [z3] => 0
                    [z4] => 0
                    [z5] => 0
                    [z6] => 0
                    [z7] => 0
                    [terrain] => Terreno
                    [rpe] => 7
                    [elevation] => 1861
                    [fc] => 140
                    [time] => 250
                    [distance] => 86
                    [training] => 

                    [color] => 
                )

            [day25112015] => stdClass Object
                (
                    [z1] => 0
                    [z2] => 0
                    [z3] => 0
                    [z4] => 0
                    [z5] => 0
                    [z6] => 0
                    [z7] => 0
                    [terrain] => Terreno
                    [rpe] => 7
                    [elevation] => 1861
                    [fc] => 140
                    [time] => 250
                    [distance] => 86
                    [training] => 

                    [color] => 
                )

            [day26112015] => stdClass Object
                (

My question is, how do I change only one value of this object? For example, only the [elevation] of [day24112015]

1 answer

1


When you executed the json_decode($data), you have obtained as return an object. To change the object attribute the way you want it, it is done so:

$d->user->season->week201548->day25112015->elevation = 0; // novo valor do atributo do valor elevation

If you had, for example, executed json_decode($data, true) (note the second argument of the method), you would have received an associative array, which you could modify as follows:

$d['user']['season']['week201548']['day25112015']['elevation'] = 0; // novo valor do atributo do valor elevation
  • Gosh, I had answered that and erased it because I didn’t know if I was right because I had no experience with json kkkk

  • Simple as that.... I was thinking of something similar, but as I was not getting it I decided to ask to remove the doubt. Thank you @Rodrigo Rigotti.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.