1 回答
TA贡献2011条经验 获得超2个赞
通常,您会使用允许您选择基础货币并以这种方式进行转换的 API。也就是说,如果您需要使用此数据集,我相信以下方法可能适合您:
$sourceCurrency = 'EUR'; // Your data source uses this as the base value
$defaultCurrency = 'USD'; // Read this from desired location
$currencies = [];
foreach ($currenciesAdmin->getAll() as $c) {
$currencies[$c['id']] = null;
}
// This is a constant
$currencies[$sourceCurrency] = 1;
$XML = new \SimpleXMLElement($XML);
foreach ($XML->Cube->Cube->Cube as $rate) {
$code = (string)$rate['currency'];
if (array_key_exists($code, $currencies)) {
$currencies[$code] = (float)$rate['rate'];
}
}
if ($defaultCurrency !== $sourceCurrency) {
// Conversion is required
$convertedCurrencies = [];
foreach (array_keys($currencies) as $code) {
$convertedCurrencies[$code] = $currencies[$code] / $currencies[$defaultCurrency];
}
$currencies = $convertedCurrencies;
}
// Use $currencies as normal with the adjusted values
下面是一个交互式演示,其中包含您可以在浏览器中测试的 JavaScript 等效代码:
(() => {
const currencyDropdown = document.querySelector('select');
const selForm = document.querySelector('form');
const sourceCurrency = 'EUR';
let cachedData = null;
const generateTable = async(first) => {
const defaultCurrency = first ? sourceCurrency : currencyDropdown.options[currencyDropdown.selectedIndex].value;
if (cachedData === null)
cachedData = await fetch('https://cors-anywhere.herokuapp.com/https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml').then(r => r.text()).then(str => (new window.DOMParser()).parseFromString(str, "text/xml"));
let currencies = Array.from(cachedData.querySelectorAll('Cube > Cube > Cube'))
.reduce((a, c) => ({ ...a,
[c.attributes.currency.value]: parseFloat(c.attributes.rate.value)
}), {});
currencies.EUR = 1;
const currencyKeys = Object.keys(currencies).sort();
currencyDropdown.innerHTML = currencyKeys.map(code => `<option${code === defaultCurrency ? ' selected' : ''}>${code}</option>`)
if (sourceCurrency !== defaultCurrency) {
const convertedCurrencies = currencyKeys.reduce((a, code) => ({
...a,
[code]: currencies[code] / currencies[defaultCurrency],
}), {});
currencies = convertedCurrencies;
}
let tbl = document.querySelector('table');
if (tbl !== null)
tbl.remove();
tbl = document.createElement('table');
tbl.innerHTML = '<tr><th>code</th><th>value</th></tr>' +
(currencyKeys.map(
code => `<tr><td>${code}</td><td>${currencies[code]} ${defaultCurrency}</td></tr>`).join(''));
document.body.appendChild(tbl);
selForm.hidden = false;
};
selForm.addEventListener('submit', (e) => {
e.preventDefault();
generateTable(false);
});
generateTable(true);
})();
<form hidden>
<label>
Default currency:
<select></select>
<input type="submit">
</label>
</form>
<table>
<tr>
<td>Loading…</td>
</tr>
</table>
- 1 回答
- 0 关注
- 221 浏览
添加回答
举报