2

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.

4
  • $result is invalid, double quotes everywhere. Commented Sep 25, 2018 at 7:37
  • 1
    Fix your $result, then use echo $get->data->id; to get the id, nothing to spectacular here. 3v4l.org/GCXU8 Commented Sep 25, 2018 at 7:39
  • @kerbholz i use this $result = json_encode(array('datas' => 'www','data' => array('id' => 1153))); Commented Sep 25, 2018 at 7:39
  • 1
    json_decode with second param as true returns associative arrays. Commented Sep 25, 2018 at 9:39

2 Answers 2

3

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

json_decode($result, true)['data']['id']
Sign up to request clarification or add additional context in comments.

4 Comments

['data']['id'] i want this is in inside variable $var . and get data return $get->$var
['data']['id'] can data->id ?
do it like this $data = json_decode($result, true)['data'] then access the id property $var = $data['id']
btw data->id is from database . so I declaration in json_decode for get data id.
1

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.

Comments

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.