php解析Json到变量

php解析Json到变量,php,json,Php,Json,我需要帮助使用php解析json到变量。我在谷歌上搜索了很多howto,但没有成功。我认为问题在于json的格式 这里是json: {“type”:“success”,“response”:{“data”:[{“id”:5,“username”:“account2”,“hostname”:“testapp.net”,“port”:8080,“status”:“enabled”,“email”:john@yourmomma.com,“servertype”:“IceCast”,“hostref”:

我需要帮助使用php解析json到变量。我在谷歌上搜索了很多howto,但没有成功。我认为问题在于json的格式

这里是json:

{“type”:“success”,“response”:{“data”:[{“id”:5,“username”:“account2”,“hostname”:“testapp.net”,“port”:8080,“status”:“enabled”,“email”:john@yourmomma.com,“servertype”:“IceCast”,“hostref”:“0.0.0.0”},{“id”:4,“用户名”:“account1”,“主机名”:“testapp2.net”,“端口”:8082,“状态”:“已禁用”,“电子邮件”:john@yourmomma.com,“服务器类型”:“ShoutCast2”,“hostref”:“0.0.0.0”}],“消息”:“2个帐户”}

棘手的部分在“响应”之后开始,“数据”开始


例如,我基本上需要将用户名、主机名和端口捕获到一个变量中,以便以后如果我想在另一个页面上显示它,可以调用它。

您需要使用
json\u decode()
。该方法的完整文档可以在中找到

从手册中:

Takes a JSON encoded string and converts it into a PHP variable.

Returns the value encoded in json in appropriate PHP type. Values true,
false and null 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.
我通常使用a来测试json是否有效。在测试json时,它看起来是正常的。您可能希望将
json\u decode()
的第二个参数设置为
true
以激活关联处理(如果您还没有)默认情况下,关联结构被解析为对象,这会导致数据类型随负载结构的变化而变化

在您的情况下,您可以通过以下方式访问
数据部分中的一个变量:

$parsed = json_decode($string);
$id = $parsed->response->data[0]->id;
在使用关联标志的位置,可以使用数组语法完全访问该标志:

$parsed = json_decode($string, true);
$id = $parsed['response']['data'][0]['id'];

虽然没有错误,但您的答案中没有代码。这可以归结为“阅读手册”@Machavity公平地说,“阅读手册”是正确的答案。@Mike:谢谢。您的答案解决了我的问题。我以前遇到的错误是“数组到字符串转换”,但那是因为我缺少[0]部分。我无法将您的答案标记为正确,因为我的声誉低于15。@Machavity不是您提供的文章的副本,因为JSON格式不同,这使任务变得困难。我的问题是数组语法。下次我将包括我的代码,并尝试更好地解释。