2

I'm trying to get currency codes from this JSON:

{
    "rates": {
        "CAD": 1.5617,
        "HKD": 8.4945,
        "ISK": 155.6,
        "PHP": 55.865,
        "DKK": 7.4674,
        "HUF": 360.02,
        "CZK": 27.312,
        "AUD": 1.7967,
        "RON": 4.8283,
        "SEK": 11.0613,
        "IDR": 17869.24,
        "INR": 82.8985,
        "BRL": 5.7001,
        "RUB": 85.9486,
        "HRK": 7.6255,
        "JPY": 118.9,
        "THB": 35.925,
        "CHF": 1.0585,
        "SGD": 1.5633,
        "PLN": 4.5506,
        "BGN": 1.9558,
        "TRY": 7.2063,
        "CNY": 7.7784,
        "NOK": 11.51,
        "NZD": 1.8417,
        "ZAR": 19.6095,
        "USD": 1.0956,
        "MXN": 26.1772,
        "ILS": 3.9018,
        "GBP": 0.88643,
        "KRW": 1341.03,
        "MYR": 4.733
    },
    "base": "EUR",
    "date": "2020-03-31"
}

I know that in Python it would be just:

for i in rates:
  print(i)

But in PHP I have a problem with that. I have tried with that:

    $length = count($exchange);
    foreach (range(0, count($exchange)) as $currency) {
        echo $response['rates'][$currency]; 
    }

but that doesn't work. It just reffers to rates[0] -> rates[33]. I tried to simple print without offset, but this doesn't work too.

3
  • 1
    foreach ($response['rates'] as $currency => $rate) Commented Mar 31, 2020 at 20:42
  • foreach ($rates as $currency => $rate) Commented Mar 31, 2020 at 20:44
  • Thanks guys. It works. :) Commented Mar 31, 2020 at 20:52

2 Answers 2

2

Make sure you use json_decode.

$arr = '{
"rates": {
"CAD": 1.5617,
"HKD": 8.4945,
"ISK": 155.6,
"PHP": 55.865,
"DKK": 7.4674,
"HUF": 360.02,
"CZK": 27.312,
"AUD": 1.7967,
"RON": 4.8283,
"SEK": 11.0613,
"IDR": 17869.24,
"INR": 82.8985,
"BRL": 5.7001,
"RUB": 85.9486,
"HRK": 7.6255,
"JPY": 118.9,
"THB": 35.925,
"CHF": 1.0585,
"SGD": 1.5633,
"PLN": 4.5506,
"BGN": 1.9558,
"TRY": 7.2063,
"CNY": 7.7784,
"NOK": 11.51,
"NZD": 1.8417,
"ZAR": 19.6095,
"USD": 1.0956,
"MXN": 26.1772,
"ILS": 3.9018,
"GBP": 0.88643,
"KRW": 1341.03,
"MYR": 4.733
},
"base": "EUR",
"date": "2020-03-31"
}';

$array = json_decode($arr, true);

foreach ($array["rates"] as $k => $v) {
    echo $k . " => " . $v . "<br>";
}

Output

Ouput

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, that's exactly what I am looking for.
Glad I could help!
0

In your case, first of all, you need to decode the JSON string:

$json_array = json_decode($json_string, true);

after, you have to take just rates with:

$rates = $json_array['orders'];

after you can loop through its items with foreach:

foreach ($rates as $rate) {
   echo $rate;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.