PHP:如何使用奇怪的“Key”名称访问Object内的Object?

时间:2016-09-01 11:14:36

标签: php json object

我有一个从远程Web服务返回的JSON对象(通过Curl调用)。对象是这样的:

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

我想如何从这个对象中访问诸如hashid之类的值?

我试过了:

$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!

请帮助。

2 个答案:

答案 0 :(得分:1)

这将有效:

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

echo $Object->$url->hash;

或者,您可以通过将第二个参数设置为\stdClass来将JSON解码为关联数组而不是true

json_decode($json, true);

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

答案 1 :(得分:1)

TRUE作为json_encode()的第二个参数传递,它返回数组,而不是对象。

然后,您只需使用通常的array access语法访问值,并使用方括号:

echo($Object['https://example.com']['hash']);
相关问题