简体   繁体   中英

PHP JSON decode - stdClass

I was having a question about making a 2D JSON string

Now I would like to know why I can't access the following:

$json_str = '{"urls":["http://example.com/001.jpg","http://example.com/003.jpg","http://example.com/002.jpg"],"alts":["testing int chars àèéìòóù stop","second description",""],"favs":["true", "false", "false"]}';

$j_string_decoded = json_decode($json_str);
// echo print_r($j_string_decoded); // OK

// test get url from second item
echo j_string_decoded['urls'][1];
// Fatal error: Cannot use object of type stdClass as array

You are accessing it with array-like syntax:

echo j_string_decoded['urls'][1];

Whereas object is returned.

Convert it to array by specifying second argument to true :

$j_string_decoded = json_decode($json_str, true);

Making it:

$json_str = '{"urls":["http://site.com/001.jpg","http://site.com/003.jpg","http://site.com/002.jpg"],"alts":["testing int chars àèéìòóù stop","second description",""],"favs":["true", "false", "false"]}';

$j_string_decoded = json_decode($json_str, true);
echo j_string_decoded['urls'][1];

Or Try this:

$j_string_decoded->urls[1]

Notice the -> operator used for objects.

Quoting from Docs:

Returns the value encoded in json in appropriate PHP type. Values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

http://php.net/manual/en/function.json-decode.php

json_decode by default turns JSON dictionaries into PHP objects, so you would access your value as $j_string_decoded->urls[1]

Or you could pass an additional argument as json_decode($json_str,true) to have it return associative arrays, which would then be compatible with $j_string_decoded['urls'][1]

Use:

json_decode($jsonstring, true);

to return an array.

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