2012-01-04 50 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