Alec Davies
Alec Davies

Reputation: 127

Parse JSON data from multiple options

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?

Upvotes: 1

Views: 65

Answers (1)

Muhammad Ibnuh
Muhammad Ibnuh

Reputation: 410

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

Upvotes: 2

Related Questions