learnprogramming learnprogramming - 1 year ago 92
JSON Question

convert json string into php object and access it's value

I have json data as shown in the picture below, how do I get highlighted value and change them?

Json Data

EDITED

I try to get the "furniture_id" using the code below...but fails...I don't know what else i can do to get the value

$test = '{"data":[{"owned_id":1,"furniture_id":1,"owned_name":"desk_123"},{"owned_id":2,"furniture_id":2,"owned_name":"chair_123"},{"owned_id":3,"furniture_id":4,"owned_name":"sofa_123"}]}';

foreach ($test as $key => $value) {
dd($furniture_id['id']);
}

Answer Source
$test = '{"data":[{"owned_id":1,"furniture_id":1,"owned_name":"desk_123"},{"owned_id":2,"furniture_id":2,"owned_name":"chair_123"},{"owned_id":3,"furniture_id":4,"owned_name":"sofa_123"}]}';
    $response=json_decode($test);

        foreach ($response->data as $key => $value) {
           echo $value->furniture_id;
echo "<br>";
        }

first you have to decode json data using json_encode method.Then if you print json decode response then you will be get an result of standard object

stdClass Object
(
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [owned_id] => 1
                    [furniture_id] => 1
                    [owned_name] => desk_123
                )

            [1] => stdClass Object
                (
                    [owned_id] => 2
                    [furniture_id] => 2
                    [owned_name] => chair_123
                )

            [2] => stdClass Object
                (
                    [owned_id] => 3
                    [furniture_id] => 4
                    [owned_name] => sofa_123
                )

        )

)

Updated

$test = '{"data":[{"owned_id":1,"furniture_id":1,"owned_name":"desk_123"},{"owned_id":2,"furniture_id":2,"owned_name":"chair_123"},{"owned_id":3,"furniture_id":4,"owned_name":"sofa_123"}]}';
$response=json_decode($test);
echo "<pre>";
print_r($response);
$newArray=[];
    foreach ($response->data as $key => $value) {
    $row=[];
       $value->furniture_id= $value->furniture_id+1;
    }
    echo "<pre>";
    print_r($response->data);

Now output will be

Array
(
    [0] => stdClass Object
        (
            [owned_id] => 1
            [furniture_id] => 2
            [owned_name] => desk_123
        )

    [1] => stdClass Object
        (
            [owned_id] => 2
            [furniture_id] => 3
            [owned_name] => chair_123
        )

    [2] => stdClass Object
        (
            [owned_id] => 3
            [furniture_id] => 5
            [owned_name] => sofa_123
        )

)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download