3

I'm playing with an API that's giving me data back in JSON format that I then json_decode() to the following format:

[stockData] => stdClass Object ( [data] => stdClass Object ( [PS3] => stdClass Object ( [2015-01-26T20:45:01Z] => stdClass Object ( [AMU] => 999.76 [ZIT] => 3.63 ) ) ) [status] => stdClass Object ( [code] => 200 [text] => ok ) ) 

I need some way of getting the 2015-01-26T20:45:01Z (which changes all the time).

I've tried get_Class() on the object, eg:

get_Class($bawsaq->stockData->data->PS3) (actually in a foreach loop)

But all that's returned is: "stdClass" and not the name. How can I get the object's name?

2
  • 3
    Why don't use the second argument to json_decode() so it returns arrays instead of objects? Commented Jan 26, 2015 at 21:36
  • 4
    2015-01-26T20:45:01Z isn't the class name, it's a property name. Commented Jan 26, 2015 at 21:37

4 Answers 4

7

It isn't actually the object's class: it's the name of the property that contains the stdClass object. So you'd need to get the first object property name from $bawsaq->stockData->data->PS3. Which is a bit tricky, actually.

It's nicer to work with arrays. If you use the $assoc parameter of json_decode, you can get an associative array instead of an object whenever a JSON object appears. This is much easier to deal with in PHP.

$bawsaq = json_decode($jsonData, true); 

You can get the key name with key:

$dateTime = key($bawsaq['stockData']['data']['PS3']); 
Sign up to request clarification or add additional context in comments.

2 Comments

Wonderful. I like dealing with objects normally, but clearly arrays are nicer in times like this. Thanks!
Generally I'll work in objects too, but almost never with stdClass ones. Glass to help.
5

When you decode the JSON, use

$bawsaq = json_decode($json, true); 

This will return associative arrays instead of stdClass objects for all the JSON objects. Then you can use

$keys = array_keys($bawsaq['stockData']['data']; $date = $keys[0]; 

Comments

1

You can use get_object_vars method.

$obj = new stdClass(); $obj->field1 = 'value1'; print_r(get_object_vars($obj)); 

Result:

Array ( [field1] => value1 ) 

Comments

0

You can use the second argument to json_decode. This will return the data as an associative array instead of an object list, so you could simply use

$input = json_decode($jsonInput, true); $key = key($input['stockData']['data']['PS3']); $data = $input['stockData']['data']['PS3'][$key]; 

or a foreach-loop. See also key on php.net.

1 Comment

That wont work it would jsut make the reference look like: $input['stockData']['data']['PS3']['2015-01-26T20:45:01Z']

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.