简体   繁体   中英

Accessing values in a JSON object, array object in PHP

When looking at the following JSON string:

$string = '{"data":{"exchange_rates":{"2":[{"cryptoCurrency":"BTC","rateForCashCurrency":{"EUR":1273.261000,"USD":1358.5694870000000000}}],"4":[{"cryptoCurrency":"BTC","rateForCashCurrency":{"EUR":1033.839000,"USD":1103.1062130000000000}}]}},"message":null,"status":"ok"}';

I can access the values of the status key in php using:

 $rates_o=json_decode($string);
 echo $rates_o->status; (using the example string above result is "ok")

Where I am completely lost is how to access the Label / values in the exchange_rates "4" EUR and USD rates in the JSON above. I think this is caused because the object is in an array in an object setup of the response?

I tried:

print_r($rates_o->data->exchange_rates->4[0]); 

but get a parse error in PHP:

PHP Parse error:  syntax error, unexpected '4' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

What is the easiest way to loop through the different currency entries and values (USD EUR, etc) in the section "4" of the JSON above?

This is my first post, I tried finding similar examples and there are many but can't find a solution to this 'nested' problem as none of the examples had any clues regarding this.

json_decode takes a second parameter to decode your json as an array,

then you would be able to access it normally as follows:

$rates_o=json_decode($string, true);
print_r($ar['data']['exchange_rates'][4][0]);

When accessing an object property that its name is an number you must put it between {}. So:

print_r($data->data->exchange_rates->{4}[0]);

Here you go:

$string = '{"data":{"exchange_rates":{"2":[{"cryptoCurrency":"BTC","rateForCashCurrency":{"EUR":1273.261000,"USD":1358.5694870000000000}}],"4":[{"cryptoCurrency":"BTC","rateForCashCurrency":{"EUR":1033.839000,"USD":1103.1062130000000000}}]}},"message":null,"status":"ok"}';
$rates_o = json_decode($string);
var_dump($rates_o->data->exchange_rates->{4}[0]);

->

object(stdClass)#4 (2) {
  ["cryptoCurrency"]=>
  string(3) "BTC"
  ["rateForCashCurrency"]=>
  object(stdClass)#5 (2) {
    ["EUR"]=>
    float(1033.839)
    ["USD"]=>
    float(1103.106213)
  }
}

What is the easiest way to loop through the different currency entries and values (USD EUR, etc) in the section "4" of the JSON above?

Could loop through exchange rates like so,

$x=array('EUR','USD');
foreach($x as $v)
    echo $rates_o->data->exchange_rates->{4}[0]->rateForCashCurrency->$v . PHP_EOL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM