I am trying to access withing foreach some of the key values in the example JSON below.
{
"Realtime Currency Exchange Rate":
{
"1. From_Currency Code": "EUR",
"2. From_Currency Name": "Euro",
"3. To_Currency Code": "USD",
"4. To_Currency Name": "United States Dollar",
"5. Exchange Rate": "1.14122552",
"6. Last Refreshed": "2018-08-14 05:07:51",
"7. Time Zone": "UTC"
},
{
"1. From_Currency Code": "USD",
"2. From_Currency Name": "United States Dollar",
"3. To_Currency Code": "EUR",
"4. To_Currency Name": "Euro",
"5. Exchange Rate": "0.87692400",
"6. Last Refreshed": "2018-08-14 05:09:17",
"7. Time Zone": "UTC"
}
}
The problem is that the keys are having spaces.
My FOREACH looks like this
$json = json_decode($data);
$json_response = array();
foreach ($json->Realtime Currency Exchange Rate as $row) {
$row_array = array();
$row_array['From'] = $row->1. From_Currency Code;
$row_array['To'] = $row->3. To_Currency Code;
$row_array['value'] = $row->5. Exchange Rate;
array_push($json_response, $row_array);
}
I have tried to use the key in the foreach statement as ['Realtime Currency Exchange Rate'], [Realtime Currency Exchange Rate], [Realtime.Currency.Exchange.Rate]
and anything else I could find in here, but none of them worked.
EDIT Also tried like this but it didn't work
foreach ($json->{'Realtime Currency Exchange Rate'} as $row) {
$row_array = array();
$row_array['From'] = $row->{'1. From_Currency Code'};
array_push($json_response, $row_array); //push the values in the array
}
But this SOLUTION worked
foreach ($json as $row) {
$row_array = array();
$row_array['From'] = $row->{'1. From_Currency Code'};
array_push($json_response, $row_array); //push the values in the array
}
Any idea how I can access the key and its value? Thanks