从json嵌套嵌套循环中提取所需信息

时间:2020-09-26 13:57:08

标签: php json

我正在使用php从硬币市值api获取实时汇率的加密货币。这是我从api得到的响应。我想从此嵌套响应中提取美元价格。我尝试了这个:

$rate = json_decode($response,true);
echo $rate['data'][0]['quotes'][0]['USD'][0];

但是没有用。我得到的json响应是:

{
  "status": {
    "timestamp": "2020-09-26T12:59:24.147Z",
    "error_code": 0,
    "error_message": null,
    "elapsed": 13,
    "credit_count": 1,
    "notice": null
  },
  "data": {
    "BTC": {
      "id": 1,
      "name": "Bitcoin",
      "symbol": "BTC",
      "slug": "bitcoin",
      "num_market_pairs": 9251,
      "date_added": "2013-04-28T00:00:00.000Z",
      "tags": [
        "mineable",
        "pow",
        "sha-256",
        "store-of-value",
        "state-channels"],
        
      "max_supply": 21000000,
      "circulating_supply": 18500450,
      "total_supply": 18500450,
      "is_active": 1,
      "platform": null,
      "cmc_rank": 1,
      "is_fiat": 0,
      "last_updated": "2020-09-26T12:58:38.000Z",
      "quote": {
        "USD": {
          "price": 10707.7229962,
          "volume_24h": 20866014910.9822,
          "percent_change_1h": -0.156013,
          "percent_change_24h": 0.675761,
          "percent_change_7d": -2.97789,
          "market_cap": 198097693905.04828,
          "last_updated": "2020-09-26T12:58:38.000Z"
        }
      }
    }
  }
}

谢谢你们的帮助!

2 个答案:

答案 0 :(得分:0)

如果仅需要获取 BTC USD 价格,请尝试这种方式,

echo $rate['data']['BTC']['quote']['USD']['price'];

否则,需要遍历API响应并从中获取值,但索引路径['quote']['USD']['price']应该与我指出的大致相同。

演示: https://3v4l.org/gi7jB

答案 1 :(得分:0)

您需要注意索引。使用关联数组(哈希图)时,不能使用数字索引。

foreach ($rate['data'] as $currency => $currencyData) {
    echo "$currency: {$currencyData['quote']['USD']['price']}\n";
}

BTC:10707.7229962