[英]Getting JSON data in PHP
我有一个像这样的JSON数据:
{
"hello":
{
"first":"firstvalue",
"second":"secondvalue"
},
"hello2":
{
"first2":"firstvalue2",
"second2":"secondvalue2"
}
}
我知道如何从对象“ first”(firstvalue)和second(secondvalue)中检索数据,但是我想循环遍历该对象并因此获得值:“ hello”和“ hello2” ...
这是我的PHP代码:
<?php
$jsonData='{"hello":{"first":"firstvalue","second":"secondvalue"},"hello2":{"first2":"firstvalue2","second2":"secondvalue2"}}';
$jsonData=stripslashes($jsonData);
$obj = json_decode($jsonData);
echo $obj->{"hello"}->{"first"}; //result: "firstvalue"
?>
能做到吗
JSON经过解码后,应该可以为您提供这种对象:
object(stdClass)[1]
public 'hello' =>
object(stdClass)[2]
public 'first' => string 'firstvalue' (length=10)
public 'second' => string 'secondvalue' (length=11)
public 'hello2' =>
object(stdClass)[3]
public 'first2' => string 'firstvalue2' (length=11)
public 'second2' => string 'secondvalue2' (length=12)
(您可以使用var_dump($obj);
来获得它)
也就是说,您正在获取一个对象,其中hello
和hello2
作为属性名称。
这意味着此代码:
$jsonData=<<<JSON
{
"hello":
{
"first":"firstvalue",
"second":"secondvalue"
},
"hello2":
{
"first2":"firstvalue2",
"second2":"secondvalue2"
}
}
JSON;
$obj = json_decode($jsonData);
foreach ($obj as $name => $value) {
echo $name . '<br />';
}
会让你:
hello
hello2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.