2010-11-02 46 views
9

我有一个关于制造2D JSON stringPHP JSON解码 - stdClass的

现在我想知道为什么我不能访问以下问题:

$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 

回答

22

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

echo j_string_decoded['urls'][1]; 

而返回的对象。

通过指定第二个参数将其转换为阵列,以true

$j_string_decoded = json_decode($json_str, true); 

使其成为:

$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]; 

或者尝试这种情况:

$j_string_decoded->urls[1] 

通知用于对象->操作者。

从文档引用:

返回 适当PHP类型在JSON编码的值。值为true, false和null(区分大小写)分别为 返回TRUE,FALSE和NULL 。如果 json无法解码,或者 编码数据比 递归限制更深,则返回NULL。

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

+0

很棒的答案,欢呼声Sarfraz – FFish 2010-11-02 18:55:06

+0

@FFISH:欢迎:) – Sarfraz 2010-11-02 18:56:42

5

用途:

json_decode($jsonstring, true); 

返回一个数组。

+0

救了我! :vvvvvv – 2017-03-25 00:39:29

7

json_decode默认变成JSON字典到PHP对象,所以你会访问你的价值$j_string_decoded->urls[1]

或者你可以通过一个额外的参数作为json_decode($json_str,true)使其返回关联数组然后将兼容$j_string_decoded['urls'][1]

+0

thanx的解释! – FFish 2010-11-02 18:55:31