-2

I'm having problems getting data from JSON with PHP.

json string

{"cpresult":{"apiversion":"2","error":"Access denied","data":{"reason":"Access denied","result":"0"},"type":"text"}}

Same json decoded

    array (
  'cpresult' => 
  array (
    'apiversion' => '2',
    'error' => 'Access denied',
    'data' => 
    array (
      'reason' => 'Access denied',
      'result' => '0',
    ),
    'type' => 'text',
  ),
)

PHP code

    $get_accounts = json_decode($get_accounts);
echo $get_accounts['cpresult']['data'][0]['result'];

error: Fatal error: Cannot use object of type stdClass as array

user1282355
  • 143
  • 2
  • 11

2 Answers2

1

json_decode will return an object by default (as opposed to an associative array). You either need to use the result with arrow pointers or add a second parameter to the json_decode call...

json_decode($json)
$get_accounts->cpresult

or

json_decode($json, true)
$get_accounts['cpresult']
jeffjenx
  • 17,041
  • 6
  • 57
  • 99
0

Well, your problem is that you think about PHP objects as they were Javascript objects. In PHP you can't access object's properties via [] like this $get_accounts['cpresult']. Instead, you should access them via -> like this $get_accounts->cpresult