gpt4 book ai didi

php - 在 PHP 中使用 foreach 解析 JSON

转载 作者:行者123 更新时间:2023-12-04 10:18:50 24 4
gpt4 key购买 nike

我正在尝试从此 JSON 获取货币代码:

{
"rates": {
"CAD": 1.5617,
"HKD": 8.4945,
"ISK": 155.6,
"PHP": 55.865,
"DKK": 7.4674,
"HUF": 360.02,
"CZK": 27.312,
"AUD": 1.7967,
"RON": 4.8283,
"SEK": 11.0613,
"IDR": 17869.24,
"INR": 82.8985,
"BRL": 5.7001,
"RUB": 85.9486,
"HRK": 7.6255,
"JPY": 118.9,
"THB": 35.925,
"CHF": 1.0585,
"SGD": 1.5633,
"PLN": 4.5506,
"BGN": 1.9558,
"TRY": 7.2063,
"CNY": 7.7784,
"NOK": 11.51,
"NZD": 1.8417,
"ZAR": 19.6095,
"USD": 1.0956,
"MXN": 26.1772,
"ILS": 3.9018,
"GBP": 0.88643,
"KRW": 1341.03,
"MYR": 4.733
},
"base": "EUR",
"date": "2020-03-31"
}

我知道在 Python 中它只是:

for i in rates:
print(i)

但是在 PHP 中我有一个问题。
我已经尝试过:

    $length = count($exchange);
foreach (range(0, count($exchange)) as $currency) {
echo $response['rates'][$currency];
}

但这不起作用。它只是指rates[0] ->rates[33]。我试图简单地打印而没有偏移,但这也不起作用。

最佳答案

确保您使用 json_decode .

$arr = '{
"rates": {
"CAD": 1.5617,
"HKD": 8.4945,
"ISK": 155.6,
"PHP": 55.865,
"DKK": 7.4674,
"HUF": 360.02,
"CZK": 27.312,
"AUD": 1.7967,
"RON": 4.8283,
"SEK": 11.0613,
"IDR": 17869.24,
"INR": 82.8985,
"BRL": 5.7001,
"RUB": 85.9486,
"HRK": 7.6255,
"JPY": 118.9,
"THB": 35.925,
"CHF": 1.0585,
"SGD": 1.5633,
"PLN": 4.5506,
"BGN": 1.9558,
"TRY": 7.2063,
"CNY": 7.7784,
"NOK": 11.51,
"NZD": 1.8417,
"ZAR": 19.6095,
"USD": 1.0956,
"MXN": 26.1772,
"ILS": 3.9018,
"GBP": 0.88643,
"KRW": 1341.03,
"MYR": 4.733
},
"base": "EUR",
"date": "2020-03-31"
}';

$array = json_decode($arr, true);

foreach ($array["rates"] as $k => $v) {
echo $k . " => " . $v . "<br>";
}

输出

Ouput

关于php - 在 PHP 中使用 foreach 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60959428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com