PHP JSON解码 - stdClass

FFi*_*ish 12 php json stdclass

我有一个关于制作2D JSON字符串的问题

现在我想知道为什么我无法访问以下内容:

$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
Run Code Online (Sandbox Code Playgroud)

Sar*_*raz 24

您正在使用类似数组的语法访问它:

echo j_string_decoded['urls'][1];
Run Code Online (Sandbox Code Playgroud)

而对象则被退回.

通过指定第二个参数将其转换为数组true:

$j_string_decoded = json_decode($json_str, true);
Run Code Online (Sandbox Code Playgroud)

进行中:

$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];
Run Code Online (Sandbox Code Playgroud)

或试试这个:

$j_string_decoded->urls[1]
Run Code Online (Sandbox Code Playgroud)

注意->操作符用于对象.

从文档引用:

以适当的PHP类型返回json中编码的值.值true,false和null(不区分大小写)分别返回为TRUE,FALSE和NULL.如果无法解码json或编码数据深于递归限制,则返回NULL.

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


Vic*_*let 7

json_decode 默认情况下,将JSON字典转换为PHP对象,因此您可以访问您的值 $j_string_decoded->urls[1]

或者你可以传递一个额外的参数,json_decode($json_str,true)让它返回关联数组,然后与之兼容$j_string_decoded['urls'][1]


net*_*der 5

使用:

json_decode($jsonstring, true);
Run Code Online (Sandbox Code Playgroud)

返回一个数组.