检索 JSON 值错误未定义偏移量:0

问题描述

一段时间以来,我一直很难从 Json url 中检索 eth 值,它不断向任何给出答案的人返回错误“未定义偏移:0”,因为它可能很容易,请考虑我是学习者和即将到来的。我的代码如下

$ethjs = "https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=0xdac17f958d2ee523a2206206994597c13d831ec7&vs_currencies=eth";
$ejson = file_get_contents($ethjs);
$ejson = json_decode($ejson,true);
$one_eth = $ejson[0]->eth;

解决方法

来自 url 的响应类似于

// https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=0xdac17f958d2ee523a2206206994597c13d831ec7&vs_currencies=eth
{
    "0xdac17f958d2ee523a2206206994597c13d831ec7": {
        "eth": 0.0003859
    }
}

上面输出的一些东西

  • 没有 [0],因为您正在尝试提取
  • 因为这似乎是支持异构数组的 PHP,所以您需要通过在 url 中传递的 contract_address 参数的值来访问它,因为它是结果对象中的 key

把它放在一起。

$ethjs = "https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=0xdac17f958d2ee523a2206206994597c13d831ec7&vs_currencies=eth";
$ejson = file_get_contents($ethjs);
$ejson = json_decode($ejson,true);
$one_eth = $ejson['0xdac17f958d2ee523a2206206994597c13d831ec7']['eth'];
echo $one_eth;