36

I'm trying to get a property from JSON data decoded into a PHP object. It's just a YouTube data API request that returns a video object that has a content object liks so;

[content] => stdClass Object
                (
                    [5] => https://www.youtube.com/v/r4ihwfQipfo?version=3&f=videos&app=youtube_gdata
                    [1] => rtsp://v4.cache7.c.youtube.com/CiILENy73wIaGQn6pSL0waGIrxMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
                    [6] => rtsp://v6.cache3.c.youtube.com/CiILENy73wIaGQn6pSL0waGIrxMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
                )

Doing

$object->content->5

Throws "unexpected T_DNUMBER" - which makes perfect sense. But how do I get the value of a property that is a number?

I'm sure I should know this. Thanks in advance.

2

3 Answers 3

83

This should work:

$object->content->{'5'}

2
  • 5
    Didn't work. Caught a Undefined property: stdClass::$5. Using PHP Version 5.5.7
    – Geo
    Commented Apr 4, 2014 at 21:59
  • 6
    This workflow DOES NOT WORK if the variable was an array that has been cast to an object. A detailed explanation and examples can be found here: stackoverflow.com/a/10333200/58795
    – Mike McLin
    Commented May 29, 2015 at 20:40
20

Another possibility is to use the 2nd parameter to json_decode:

$obj = json_decode(str, true);

You get an array instead of a PHP object, which you can then index as usual:

$obj['content'][5]
0
2

JSON encode, and then decode your object passing true as the second param in the decode function. This will return an associative array.

$array = json_decode(json_encode($object), true);

Now you can use your new array

echo $array['content']['5'];

Using $object->content->{'5'} will not work if the object was created by casting an array to an object.

A more detailed description can be found here: https://stackoverflow.com/a/10333200/58795

Not the answer you're looking for? Browse other questions tagged or ask your own question.