PHP JSON解码-stdClass [英] PHP JSON decode - stdClass

查看:180
本文介绍了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

解决方案

您正在使用类似数组的语法对其进行访问:

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]

请注意用于对象的->运算符.

从文档中引用:

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

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

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

这篇关于PHP JSON解码-stdClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆