亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

正確轉換貨幣

正確轉換貨幣

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 關注
  • 254 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號