Dhiemas Ganisha
Dhiemas Ganisha

Reputation: 223

Get some data using json decode

I have array like this

$result = "{
  "datas": "www",
  "data": {
    "id": 1153
  }
}";

$get = json_decode($result);

I want to get id in object data. I use $param = "data->id" but it doesn't work and I get an error Undefined property: stdClass::$data->id , but if I get datas by using $param = "datas", it works. to get data I use return $get->$param .

How to get id ? sorry for my english.

Upvotes: 2

Views: 266

Answers (2)

Anjana Silva
Anjana Silva

Reputation: 9221

Try this,

$json = '{"datas":"www","data":{"id":1153}}';
$obj = json_decode($json);
echo $obj->datas; //this returns datas
echo '<br/>';
echo $obj->data->id; //this returns data id

Note that $json string wrapped with single quotes not double quotes. Individual items wrapped with double quotes.

Upvotes: 1

After decoding the json will be handled as an array, try to access the property like this:

json_decode($result, true)['data']['id']

Upvotes: 3

Related Questions