You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP提取JSON中动态键对应的加密货币USD价格?

问题:提取动态顶级键下的加密货币USD价格

我正尝试在WordPress的一个目录中引入API数据,仅需获取加密货币的USD价格,无需其他信息,但因数据为嵌套格式,目前无法成功提取。

示例JSON数据:

{
  "bitcoin": {
    "usd": 16808.82 
  }
}

我的PHP代码:

<?php
$handle = curl_init();
$url = get_post_meta($entity->post()->ID, '_drts_field_004', true);

// Set the url
curl_setopt($handle, CURLOPT_URL, $url);
// Set the result output to be a string.
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);

$output = curl_exec($handle);
         
curl_close($handle);

$data = json_decode($output);
echo $output;
var_dump($data);

执行结果:

{
    "bitcoin":{
        "usd":16833.02
        }
}    
object(stdClass)#10399 (1) { 
    ["bitcoin"]=> object(stdClass)#10492 (1) { 
        ["usd"]=> float(16833.02) 
        } 
}

本例中我仅需获取数值16833.02,且需适配多种加密货币,其中"usd"键固定,但顶级键(如"bitcoin")会随币种变化。请问如何仅输出该价格数值?我尝试过多种echo写法均未成功,是否可以类似echo $data['bitcoin']['usd'];的写法,但将"bitcoin"替换为通配符以匹配任意顶级键?


解决方法

方案1:转关联数组提取价格

把JSON解码为关联数组,利用reset()获取第一个顶级键对应的内容,直接提取usd值:

<?php
$handle = curl_init();
$url = get_post_meta($entity->post()->ID, '_drts_field_004', true);

curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);

$output = curl_exec($handle);
curl_close($handle);

// 解码为关联数组
$data = json_decode($output, true);
// 获取第一个顶级键的usd价格
$price = reset($data)['usd'];
echo $price;

方案2:直接处理对象

如果保留默认的对象格式,用get_object_vars()将对象转为数组后再提取:

<?php
$handle = curl_init();
$url = get_post_meta($entity->post()->ID, '_drts_field_004', true);

curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);

$output = curl_exec($handle);
curl_close($handle);

$data = json_decode($output);
// 提取第一个顶级对象的usd属性
$price = reset(get_object_vars($data))->usd;
echo $price;

关键说明

  • reset()函数可以直接获取数组的第一个元素,完美适配顶级键动态变化的场景
  • 两种方案都能精准提取usd对应的价格数值,无需关心当前币种的顶级键名称

内容的提问来源于stack exchange,提问作者Arctic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:31:58