php - 使用 Api 的货币转换算法

标签 php algorithm currency

我目前正在使用 PHP 开发一个应用程序,用户可以像 ebay 或 aliexpress 那样更改产品的货币货币。因此,如果用户将其货币更改为美元,则所有产品价格都将转换为美元。

我搜索了一个名为 CurrencyLayer 的 API 来获取实时货币。 API 提供以下结构:

"success": true,
  "terms": "https://currencylayer.com/terms",
  "privacy": "https://currencylayer.com/privacy",
  "timestamp": 1432480209,
  "source": "USD",
  "quotes": {
    "USDAED": 3.67315,
    "USDAFN": 60.790001,
    "USDALL": 126.194504,
    "USDAMD": 477.359985,
    "USDANG": 1.790403,
    [...]
  }

我的计划是每小时将这些报价保存在我的数据库中。考虑一个转换货币的函数,将一种货币转换成另一种货币的正确算法是什么?我知道这并不难,但我想不通。

function convertCurrency($currency1 = 'USD', $currency2 = 'EUR', $value){
   //Search the currency value and algorithm to convert   
   $newValue = (????)
   return $newValue;
}

最佳答案

请注意,由于结果看起来是 JSON 格式,您可能首先要调用 json_decode以 PHP 对象格式获取结果。

json_decode 之后的 API 示例如下所示:

    // var_dump($api_result)
    stdClass Object
    (
        [success] => 1
        [terms] => https://currencylayer.com/terms
        [privacy] => https://currencylayer.com/privacy
        [timestamp] => 1432480209
        [source] => USD
        [quotes] => stdClass Object
            (
                [USDAED] => 3.67315
                [USDAFN] => 60.790001
                [USDALL] => 126.194504
                [USDAMD] => 477.359985
                [USDANG] => 1.790403
            )
    )

下一步是使用您的函数组合两个参数以访问(例如)USDAED 结果:

<?php

    function convertCurrency($currency1 = 'USD', $currency2 = 'EUR', $value) {
        //Search the currency value and algorithm to convert
        $combined_currencies = $currency1.$currency2;
        return $api_result->quotes->$combined_currencies * $value;
    }

    echo convertCurrency("USD", "AED", 1); // 3.67315

关于php - 使用 Api 的货币转换算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50283127/

相关文章:

PHP 不显示错误 - 内部服务器错误 (500)

c# - 为货币格式化文本框字符串

iphone - 我在哪里可以找到更新的实时汇率?

php - 使用 LIKE 的 Mysql 搜索框

php - MySQL 更新查询,where 条件仅更新一条记录

algorithm - 我应该如何过滤这些数据?

algorithm - 以下如何等同于 O(N)

algorithm - 合流持久化的实际应用

javascript - JavaScript 是否有 Money 类?

PHP:mysql_connect() 返回 true 但 mysql_select_db() 返回 false _ 在 Ubuntu 更新后