【问题标题】:Array Index is empty, accessing JSON object数组索引为空,访问 JSON 对象
【发布时间】:2018-02-16 09:51:26
【问题描述】:

我正在调用以下 API url:https://api.gemini.com/v1/trades/btcusd?timestamp=1518710400&limit_trades=1

这将返回以下 JSON:

[
     {
         "timestamp":1518710409,    
         "timestampms":1518710409004,
         "tid":3051346543,
         "price":"9837.17",
         "amount":"0.00118501",
         "exchange":"gemini",
         "type":"sell"
      }
]

当我尝试像这样从 json 字符串访问“价格”对象时:

$response = $client->request('GET', 'https://api.gemini.com/v1/trades/btcusd?timestamp=1518710400&limit_trades=1');
$body     = json_decode($response->getBody());

var_dump() 返回:

array(1) { [0]=> object(stdClass)#85 (7) { ["timestamp"]=> int(1518710409) ["timestampms"]=> float(1518710409004) ["tid"]=> float(3051346543) ["price"]=> string(7) "9837.17" ["amount"]=> string(10) "0.00118501" ["exchange"]=> string(6) "gemini" ["type"]=> string(4) "sell" } } 

但我收到以下错误:

Notice: Trying to get property of non-object in (file path) on line 130

第 130 行正在

echo $body->price

为什么$body->price 不是从 JSON 字符串返回的“价格”的有效访问器?

【问题讨论】:

  • 您的 JSON 响应是一个对象数组。

标签: php json guzzle


【解决方案1】:

$body 是一个数组,因此您需要执行以下操作,因为它是该数组中的第一项:

$body[0]->price;

【讨论】:

  • 谢谢,就是这样 - 事后看来非常简单的问题。欣赏第二双眼睛!
  • 只要知道答案,一切都会变得简单!
猜你喜欢
  • 1970-01-01
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
相关资源
最近更新 更多