夏期劇場 夏期劇場 - 3 months ago 11
JSON Question

PHP : How to access Object inside Object with weird "Key" name?

I have a JSON Object returned from the remote Web Service (via Curl call). The Object is something like this:

stdClass Object ( [https://example.com] => stdClass Object ( [hash] => 8 [id] => 277 ) )


How am i suppose to access the values like:
hash
,
id
from this Object please?

I tried:

$Object = json_decode( $curl_return );

echo $Object->hash; // Didn't work!
echo $Object[0]->hash; // Didn't work!
echo $Object[0]['hash']; // Didn't work!
echo $Object['https://example.com']->hash; // Didn't work!


Please kindly help.

Answer

This will work:

$url = 'https://example.com';

echo $Object->$url->hash;

Alternatively you can decode the JSON to an associative array instead of a \stdClass by setting the second argument to true with:

json_decode($json, true);

https://secure.php.net/manual/en/function.json-decode.php

Comments