[英]Getting JSON data in PHP
I have a JSON data like this: 我有一个像这样的JSON数据:
{
"hello":
{
"first":"firstvalue",
"second":"secondvalue"
},
"hello2":
{
"first2":"firstvalue2",
"second2":"secondvalue2"
}
}
I know how to retrieve data from object "first" (firstvalue) and second (secondvalue) but I would like to loop trough this object and as a result get values: "hello" and "hello2"... 我知道如何从对象“ first”(firstvalue)和second(secondvalue)中检索数据,但是我想循环遍历该对象并因此获得值:“ hello”和“ hello2” ...
This is my PHP code: 这是我的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"
?>
Can it be done? 能做到吗
The JSON, after being decoded, should get you this kind of object : 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)
(You can use var_dump($obj);
to get that) (您可以使用
var_dump($obj);
来获得它)
ie you're getting an object, with hello
and hello2
as properties names. 也就是说,您正在获取一个对象,其中
hello
和hello2
作为属性名称。
Which means this code : 这意味着此代码:
$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 />';
}
Will get you : 会让你:
hello
hello2
This will work because foreach
can be used to iterate over the properties of an object -- see Object Iteration , about that. 这将起作用,因为可以使用
foreach
来迭代对象的属性-有关此信息,请参见对象迭代 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.