json字符串,使用php访问不同的{}对象 [英] json string accessing different {} objects with php
问题描述
我要解析的字符串中包含一些JSON代码.我还没有使用JSON,所以这是一个简单的问题.
I have some JSON code in a string that I am trying to parse. I havent used JSON much so this is prolly a simple question.
就像:
$json_code ="
{
"key1":"value",
"key2":"value"
},
{
"key3":"value",
"key4":"value"
}";
在尝试用php遍历所有不同对象(?-花括号的集合)时遇到问题.
Im having problems trying to loop through all of different Objects(? - the sets of curly braces) with php.
非常感谢您的帮助
谢谢, 布莱恩
推荐答案
您不能在PHP中使用这样的JSON文字.将其转换为字符串(用引号引起来),然后使用json_decode()
以类似对象的方式访问它.
You can't use a JSON literal in PHP like that. Turn it into a string (wrap it in quotes), and then use json_decode()
to access it in an object like manner.
如果您希望像访问数组一样访问它,请将json_decode()
的第二个参数设置为TRUE
.
If you'd prefer to access it like an array, set json_decode()
's second argument to TRUE
.
我看到您已将其用引号引起来-现在必须转义内部引号.
I see you have wrapped it in quotes - you must now escape the inner quotes.
要遍历它,只需对json_decode()
返回的对象或数组使用foreach()
.
To loop through it, just use foreach()
on the object or array returned from json_decode()
.
要使通过json_decode()
解析后的结构可视化,请使用var_dump()
.
To visualise the structure once parsed via json_decode()
, use var_dump()
.
您的问题是,您的JSON不正确-它有2个对象,但没有数组文字语法.您需要使用[]
包装该结构.
Your problem is, your JSON is not proper - it has 2 objects, but not in array literal syntax. You need to wrap that structure with []
.
看到它.
这篇关于json字符串,使用php访问不同的{}对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!