获取子数组的值

问题描述 投票:1回答:2

我正在尝试使用此api链接获得当前的美元/欧元汇率:

http://api.fixer.io/latest?base=USD&symbols=EUR

使用此代码:

$url = "http://api.fixer.io/latest?base=USD&symbols=EUR";
$json = json_decode(file_get_contents($url), true);
$price = $json->rates[0]->EUR;

我想要$price的结果像:"0.84782",但似乎我做错了什么?

php json
2个回答
1
投票
<?php

$url = "http://api.fixer.io/latest?base=USD&symbols=EUR";
$json = json_decode(file_get_contents($url), true);
$price=$json['rates']['EUR'];
echo $price;

这对你有用。您要查找的价格是嵌套数组,因此您必须首先访问父级数据。


0
投票

您正在将true传递给json_decode,因此返回的值是一个数组。要使用对象,请删除true,如下所示:

$json = json_decode(file_get_contents($url));

像这样访问它:

echo $json->rates->EUR; // Output is: 0.84782

如果要访问数组样式:

$json = json_decode(file_get_contents($url), true);
echo $json['rates']['EUR']; // 0.84782
© www.soinside.com 2019 - 2024. All rights reserved.