数组索引为空,访问JSON对象

时间:2018-02-16 01:24:36

标签: php json guzzle

我正在调用以下API网址: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字符串访问'price'对象时,如下所示:

$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字符串返回的'price'的有效访问者?

1 个答案:

答案 0 :(得分:2)

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

$body[0]->price;