【问题标题】:Why type of array is this? [duplicate]为什么是这种类型的数组? [复制]
【发布时间】:2013-07-20 02:55:19
【问题描述】:

好的,所以我正在使用 coinbase 的 API 来获取 BTC 的当前价格,但是当我尝试使用 json_decode() 时它返回一个错误,这让我相信他们的响应不是 JSON。

https://coinbase.com/api/v1/prices/spot_rate?currency=USD

返回:

{"amount":"90.00","currency":"USD"}

我试过 json_decode($grabPrice); $grabPrice 等于该 API 的 file_get_contets()。它给我的错误是:

Catchable fatal error: Object of class stdClass could not be converted to string in

如何获取 PHP 变量中的金额?

谢谢。

【问题讨论】:

  • 什么错误?据我所知,它是 JSON。
  • 我试过 json_decode($grabPrice); $grabPrice 等于该 API 的 file_get_contets()。它给我的错误是: Catchable fatal error: Object of class stdClass could not be convert to string in
  • 那是因为你试图打印返回的值,在这种情况下是一个对象....echo $returnedFromJsonDecode->amount;
  • 如果您认为响应不是 JSON,请在询问之前通过 jsonlint.com 运行它。如果您不确定 json_decode 返回的内容,请在询问之前先对其进行 var_dump。如果您收到错误消息,请在询问之前先搜索一下。

标签: php arrays json


【解决方案1】:

这是一个 json 编码的字符串 ....

要从中获取数据,请先使用json_decode

 $data = json_decode($str);

 echo $data->amount;

或者如果你更喜欢数组而不是对象

 $data = json_decode($str, true);
 echo $data["amount"];

【讨论】:

  • 这是一个工作演示,因为你打败了我(坏笑话):codepad.org/y2sXrUXf
  • 阅读我的编辑/评论。
【解决方案2】:

这段代码运行良好:-

 $grab=file_get_contents('https://coinbase.com/api/v1/prices/spot_rate?currency=USD');
    $resarray=json_decode($grab);
echo 'amount :'.$resarray->amount.'<br>';
echo 'currency :'.$resarray->currency;

输出:-

amount :89.91
currency :USD

【讨论】:

    猜你喜欢
    • 2012-03-18
    • 2014-04-03
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 2014-11-06
    • 2015-02-18
    • 1970-01-01
    相关资源
    最近更新 更多