在这个示例How to decode a JSON String中,我知道如何在您的帮助下用一个对象解码一个JSON字符串
但是现在我想用几个对象来改进对JSON字符串的解码,但我不知道该怎么做。
下面是一个示例:
{ "inbox": [
{ "firstName": "Brett", "lastName":"McLaughlin" },
{ "firstName": "Jason", "lastName":"Hunter" },
{ "firstName": "Elliotte", "lastName":"Harold" }
],
"sent": [
{ "firstName": "Isaac", "lastName": "Asimov" },
{ "firstName": "Tad", "lastName": "Williams" },
{ "firstName": "Frank", "lastName": "Peretti" }
],
"draft": [
{ "firstName": "Eric", "lastName": "Clapton" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff" }
]
}
发布于 2010-04-01 20:06:40
您可以使用函数来解码JSON字符串:
$json = <<<JSON
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin" },
{ "firstName": "Jason", "lastName":"Hunter" },
{ "firstName": "Elliotte", "lastName":"Harold" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov" },
{ "firstName": "Tad", "lastName": "Williams" },
{ "firstName": "Frank", "lastName": "Peretti" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff" }
]
}
JSON;
$data = json_decode($json);
然后,要查看数据的外观,您可以将其转储:
var_dump($data);
您将看到一个包含三个数组的对象,每个数组包含其他子对象:
object(stdClass)[1]
public 'programmers' =>
array
0 =>
object(stdClass)[2]
public 'firstName' => string 'Brett' (length=5)
public 'lastName' => string 'McLaughlin' (length=10)
1 =>
object(stdClass)[3]
public 'firstName' => string 'Jason' (length=5)
public 'lastName' => string 'Hunter' (length=6)
...
public 'authors' =>
array
0 =>
object(stdClass)[5]
public 'firstName' => string 'Isaac' (length=5)
public 'lastName' => string 'Asimov' (length=6)
...
这意味着你知道如何访问你的数据。
例如,要显示程序员列表,您可以使用:
foreach ($data->programmers as $programmer) {
echo $programmer->firstName . ' ' . $programmer->lastName . '<br />';
}
这将使您获得以下输出:
Brett McLaughlin
Jason Hunter
Elliotte Harold
https://stackoverflow.com/questions/2560096
复制相似问题