PHP JSON decode - stdClass

对着背影说爱祢 提交于 2019-12-18 19:09:14

问题


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

回答1:


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




回答2:


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]




回答3:


Use:

json_decode($jsonstring, true);

to return an array.



来源:https://stackoverflow.com/questions/4080755/php-json-decode-stdclass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!