Benvaulter
Benvaulter

Reputation: 249

get data from json array in php

I am having trouble accessing information in a json-Array that I retrieved using php's json_decode function.

the json-file looks as follows:

{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":XXX,"currencySign":"€","email":"[email protected]","code":0}]},"result":"success"}

I used the following php code to get the contents:

$json = file_get_contents($json_url);
$data = json_decode($json,true);
echo '<pre>' . print_r($json, true) . '</pre>';

The result print_r displays looks just like what I expect and looks like the json.

However, I cannot figure out to access the variables. Whenever I try something like

$test = $json['model']['results']['balance'];

the script throws an error, which I can't identify. I already figured out if I access the $json variable like so:

$test = $json[n]; // returns the nth character, e.g. n = 0 $test = "{", n = 2 $test = "c"

The script also did not throw an error if I tried accessing the variable like so:

$test = $json['code']; // returns "{"

Can someone help me figure out how to navigate this array?

Thanks!

Upvotes: 2

Views: 7070

Answers (3)

Florian Moser
Florian Moser

Reputation: 2663

You recieve an error similar to Cannot use object of type stdClass as array in (...) right?

json_decode returns an object of the type stdClass which is the only object in php (as far as I know) which properties cannot be accessed like an array. You will have to access them as follows:

$json = '{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":"XX","currencySign":"€","email":"[email protected]","code":0}]},"result":"success"}';
$obj = json_decode($json);
var_dump($obj->message); //works
var_dump($obj["message"]); //throws exception

Upvotes: 1

Erik Nohlmans
Erik Nohlmans

Reputation: 1

There is an error in the JSON array. "firstDepositDate": XXX is not a valid value. Should be a string "XXX".

Also you are trying to the wrong variable. The decoded data should be a PHP array. In this case $data['code'] instead of $json['code']

Upvotes: 0

Mr. Llama
Mr. Llama

Reputation: 20889

The results key is a true array, not an unordered map (key/value). Additionally, you should be accessing the decoded $data, not the $json string.

This should work for you:

$test = $data['model']['results'][0]['balance'];

This is what should have tipped you off:

{"results":[{"message"
^          ^
|          |
|          \-- Start of an array
|
\-- Start of an object

Upvotes: 4

Related Questions