【问题标题】:Retrieve JSON Value error Undefined offset: 0检索 JSON 值错误未定义的偏移量:0
【发布时间】:2021-05-25 03:14:51
【问题描述】:

一段时间以来,我一直很难从 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;

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    来自 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;
    

    【讨论】:

    • 那么为了获取 eth 值,你建议我如何格式化代码?我迷路了。
    • 你将不得不做类似$one_eth = $ejson['0xdac17f958d2ee523a2206206994597c13d831ec7']['eth'];
    • 现在抛出错误“使用未定义的常量 eth - 假定为 'eth'(这将在 PHP 的未来版本中抛出错误)”
    • 同样当我这样做 $one_eth = $ejson['0xdac17f958d2ee523a2206206994597c13d831ec7'];它回显 "eth": 0.0003859 当我只想计算 eth 的值时。
    • @Basil Moses,看看更新的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 2014-06-25
    相关资源
    最近更新 更多