Martijn
Martijn

Reputation: 28

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.

Upvotes: 0

Views: 1933

Answers (4)

zrinath
zrinath

Reputation: 106

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;

Upvotes: 0

hassan
hassan

Reputation: 8308

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]);

Upvotes: 3

Gab
Gab

Reputation: 3520

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)
  }
}

Upvotes: -1

aperpen
aperpen

Reputation: 728

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]);

Upvotes: 1

Related Questions