【问题标题】:PHP : How to access Object inside Object with weird "Key" name? [duplicate]PHP:如何使用奇怪的“键”名称访问对象内部的对象? [复制]
【发布时间】:2016-09-01 11:14:35
【问题描述】:

我有一个从远程 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!

请帮忙。

【问题讨论】:

标签: php json object


【解决方案1】:

这将起作用:

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

echo $Object->$url->hash;

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

json_decode($json, true);

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

【讨论】:

    【解决方案2】:

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

    然后您所要做的就是使用通常的array access 语法访问这些值,并带有方括号:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      相关资源
      最近更新 更多