Skip to content
Advertisement

Parsing JSON with foreach in PHP

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement