Search code examples
phpjsoncurrency

Conversion. USD to custom currency


So I've been trying to convert USD to FMC, FMC to USD, GBP to FMC, FMC to GBP, EUR to FMC, FMC to EUR

I just can't seem to figure out how to convert it. I realize it's probably more math related, but could someone point me in the correct direction. I don't want ti done for me. Just need another pair of eyes.

$url = "http://femicoin.cf/rate.json";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$FMC = $data[1]["rate"];

http://femicoin.cf/rate.json holds all the currency values.

I'm making a cryptocurrency for a project me and my buds thought of. Just to joke around with.


Solution

  • Json returned by the URL is
    [ {"code":"FMC","name":"Femicoin","rate":0.023}, {"code":"USD","name":"US Dollar","rate":1}, {"code":"GBP","name":"British Pound","rate":1.25}, {"code":"EUR","name":"Euro","rate":0.94} ]

    1. Decode Json into an array. $jsonArr = json_decode($json, true);

    2. If sequence of currencies remain same then fetch the rate.
      $fmc = $jsonArr[0]["rate"]; $usd = $jsonArr[1]["rate"]; $gbp = $jsonArr[2]["rate"]; $eur = $jsonArr[3]["rate"];

    If sequence changes, then you may have to iterate the array to set desired currency rate into variable.

    1. You can create a function like
      convertCurrency($from, $to, $value) { return ($value * $to) / $from; }
    2. Now,if you want to convert 100 USD to FMC
      then call the function
      $result = convertCurrency($usd, $fmc, 100)

    Similarly, FMC to USD :: convertCurrency($fmc, $usd, 100)

    GBP to FMC :: convertCurrency($gbp, $fmc, 100)

    FMC to GBP :: convertCurrency($fmc, $gbp, 100)

    EUR to FMC :: convertCurrency($eur, $fmc, 100)

    FMC to EUR :: convertCurrency($fmc, $eur, 100)

    Replace 100 by $value that you want to convert.