我正在使用API获得以下响应:
{"BTC_LTC":{"last":"0.0251","lowestAsk":"0.02589999","highestBid":"0.0251","percentChange":"0.02390438",
"baseVolume":"6.16485315","quoteVolume":"245.82513926"},"BTC_NXT":{"last":"0.00005730","lowestAsk":"0.00005710",
"highestBid":"0.00004903","percentChange":"0.16701570","baseVolume":"0.45347489","quoteVolume":"9094"}, ... }
当我知道像
这样的密钥时访问对象没问题$result = json_decode(file_get_contents($url));
$result->BTC_LTC->last
在我的情况下,我不知道XXX_XXX键。我怎样才能获得钥匙?我尝试过$ result-> {0} / $ result-> [0] / $ result {0} / $ result [0]等内容但没有成功。
如何检索XXX_XXX的值(例如,在BTC_LTC上面的示例中)?
答案 0 :(得分:1)
使用应该起作用的foreach循环
foreach($result as $k=>$v)
{
.
.
.
}
答案 1 :(得分:1)
这应该可以解决问题:
<?php
$json = '{"BTC_LTC":{"last":"0.0251","lowestAsk":"0.02589999","highestBid":"0.0251","percentChange":"0.02390438",
"baseVolume":"6.16485315","quoteVolume":"245.82513926"},"BTC_NXT":{"last":"0.00005730","lowestAsk":"0.00005710",
"highestBid":"0.00004903","percentChange":"0.16701570","baseVolume":"0.45347489","quoteVolume":"9094"}}';
$result = json_decode($json);
$vars = get_object_vars($result);
$keys = array_keys($vars);
echo $vars[$keys[0]]->last;
?>
您可以尝试代码here
答案 2 :(得分:0)
json_decode
的第二个参数允许指定您想要返回一个数组:
$result = json_decode(file_get_contents($url),true);
现在结果是一个数组,你可以照常使用它(循环,array_keys,e.t.c。)。