0

i get object from json like this

{"valid":"yes","date":"2017-01-04","data-val":{"current":25}}

i want to get current value i create a var include name current

$johndoe = 'current';

but i fail to call it like this :

$currentjohn = $data['data-val'][$johndoe];

fail

$currentjohn = $data['data-val']['.$johndoe.'];

also fail

$currentjohn = $data['data-val']->$johndoe;

fail too

how to do it right way or how to get 'current' if i didn't know that key name is current

thank you for helping

imunisasi
  • 3
  • 1

1 Answers1

1

As an object the syntax is:

$data->{'data-val'}->$johndoe;

(the curly braces need to be used because of the hyphen in the name. This is an object, not an array.)

Demo: https://eval.in/709782

as an array:

$data['data-val'][$johndoe];

Demo: https://eval.in/709784

A variable in single quotes will not be a variable and you can't concatenate in quotes. So:

$currentjohn = $data['data-val']['.$johndoe.'];

had a couple issues.

chris85
  • 23,846
  • 7
  • 34
  • 51