2012-01-04 49 views
0

我试图在PHP中构建货币换算功能。使用存储在JSON文件中的费率进行货币转换

我已将所有费率缓存在JSON文件中。 (https://raw.github.com/currencybot/open-exchange-rates/master/latest.json)

我的脚本从URL像这样获取值:

.COM amnt = 10 &从= USD &到= GBP

我访问率,由这些值,像这样:

$string = file_get_contents("cache/latest.json"); 
    $jsonRates = json_decode($string, true); 

    foreach ($jsonRates as $rates => $rate) { 
     $fromRate = $rate[$from]; 
     $toRate = $rate[$to]; 
    } 

现在我被困。我有我需要的一切,我只是不知道该怎么办。在这种特定情况下,如何将$ amnt变量从USD转换为GBP。

谢谢!

回答

2

您正在寻找类似的东西,但这只适用于美元。

$string = file_get_contents("cache/latest.json"); 
    $jsonRates = json_decode($string, true); 

    foreach ($jsonRates["rates"] as $currency => $rate) { 
     if($currency==$_GET["to"]) { 
      echo $_GET["amnt"] * $rate; 
      break; 
     } 
    } 

试试这个做所有的转换:

echo number_format(($_GET["amnt"]/$jsonRates["rates"][$_GET["from"]])*$jsonRates["rates"][$_GET["to"]],3); 
+0

作品的魅力。我不知道它会像使用一个PHP函数的一行代码一样简单。非常感谢! – tctc91 2012-01-05 00:34:37