Chuck Le Butt
Chuck Le Butt

Reputation: 48826

Getting the name of a stdClass object in PHP

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?

Upvotes: 3

Views: 6391

Answers (4)

Sebb
Sebb

Reputation: 911

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.

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 238115

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']);

Upvotes: 7

Barmar
Barmar

Reputation: 782785

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];

Upvotes: 5

Piotr Olaszewski
Piotr Olaszewski

Reputation: 6224

You can use get_object_vars method.

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

print_r(get_object_vars($obj));

Result:

Array
(
    [field1] => value1
)

Upvotes: 1

Related Questions