为了账号安全,请及时绑定邮箱和手机立即绑定

正确转换货币

正确转换货币

PHP
大话西游666 2021-12-03 18:53:32
我有一个默认货币为美元。下面的课程部分允许转换不同的货币,但我的问题是转换总是基于欧元作为默认值。如果选择了如何更新函数以使用美元作为默认值?谢谢EUR = 1(默认)USD = 1.10 这种方法适用于任何货币EUR = 0.9 USD = 1(默认) 这种方法不起作用,因为美元处于默认状态,结果总是如上。注意: $currenciesAdmin->getAll()以所有带有代码(EUR)和标题(Euro)的货币为例。EUR 的值始终为 null,因为该转换基于 EUR 作为默认值(有关值,请参阅链接 ecb.europa.eu)public function getConvertCurrency(){  $currenciesAdmin = new CurrenciesAdmin();  $XML = HTTP::getResponse([    'url' => 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'  ]);  if (empty($XML)) {    throw new \Exception('Can not load currency rates from the European Central Bank website');  }  $currencies = [];  foreach ($currenciesAdmin->getAll() as $c) {    $currencies[$c['id']] = null;  }  $XML = new \SimpleXMLElement($XML);  foreach ($XML->Cube->Cube->Cube as $rate) {    if (array_key_exists((string)$rate['currency'], $currencies)) {      $currencies[(string)$rate['currency']] = (float)$rate['rate'];    }  }  foreach ($currencies as $code => $value) {    if (!is_null($value)) {      try {        $this->db->save('currencies', [          'value' => $value,          'last_updated' => 'now()'        ], [          'code' => $code        ]);      } catch (\PDOException $e) {        trigger_error($e->getMessage());      }    }  }}
查看完整描述

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&hellip;</td>

  </tr>

</table>


查看完整回答
反对 回复 2021-12-03
  • 1 回答
  • 0 关注
  • 221 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信