1

I'm trying to parse JSON data in the format [{code:SE rate:1.294},{code:UK rate:2.353}] from this page: http://www.mycurrency.net/service/rates

I have implemented an IP reader that detects the users location in a 2 letter country code. I want to pluck the correct data from that link with 'code' and return the value 'rate'. I was thinking I might have to do a foreach loop to iterate through all the countries?

Alec Davies
  • 127
  • 11
  • 1
    Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – Rajdeep Paul Aug 12 '17 at 13:20
  • Plus you haven't posted any code with your question, so that makes it *unclear what you're asking*. – Rajdeep Paul Aug 12 '17 at 13:23
  • by the way, the data from [http://www.mycurrency.net/service/rates](http://www.mycurrency.net/service/rates) is not accurate, its shows my country Indonesia as "East Timor" but the currency was IDR (Indonesian Rupiah) while East Timor/TP currency is USD – Muhammad Ibnuh Aug 12 '17 at 14:01
  • @RajdeepPaul Honestly, I didn't know where to start, this is all new to me. – Alec Davies Aug 12 '17 at 15:51
  • @MuhammadIbnuh Good spot, it's the best freesource data I could find, maybe I can convert that within my script – Alec Davies Aug 12 '17 at 15:52

1 Answers1

2

This is my code, I hope this is what are you looking for.

First I create a new array $output to make it more easy to search

$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);

foreach ($json as $key => $data) {
    $output[$key]['code'] = $data['code'];
    $output[$key]['rate'] = $data['rate'];
}

After that we use a function to search value in array and returning the key. I got it from here

function searchForRate($countryCode, $array) {
   foreach ($array as $key => $val) {
       if ($val['code'] === $countryCode) {
           return $key;
       }
   }
   return null;
}

and then I run the function with the first parameter as country code to get the keys of specific country code.

$find = searchForRate("BT", $output);

And then echo the rates from our $output array by key in $find variable

echo 'RATE = '.$output[$find]['rate'];

This is the complete codes

<?php

$string = file_get_contents("http://www.mycurrency.net/service/rates");
$json = json_decode($string, true);

foreach ($json as $key => $data) {
    $output[$key]['code'] = $data['code'];
    $output[$key]['rate'] = $data['rate'];
}

function searchForRate($countryCode, $array) {
   foreach ($array as $key => $val) {
       if ($val['code'] === $countryCode) {
           return $key;
       }
   }
   return null;
}

$find = searchForRate("BT", $output);
echo 'RATE = '.$output[$find]['rate'];

Example output:

RATE = 64.13
Muhammad Ibnuh
  • 360
  • 5
  • 14