这样的JSON在PHP中如何使用?

yueyang 2008-04-16 04:01:35
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
}
已经得到$test如上
我知道$test->authors可以得到authors的值
但authors下的第一列firstName的值该如何取呢?
$test->authors->firstName 这样是不对的。
js中可以test.authors(0).firstName
PHP中如何写才能得到正确的值呢?
...全文
94 3 打赏 收藏 举报
写回复
3 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
SysTem128 2008-05-30

<?php
$jsonData = '{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
} ';
$arr = json_decode($jsonData,true);
print_r($arr);die("|end");
?>
  • 打赏
  • 举报
回复
yueyang 2008-04-16
恩确实可以,其实我的代码不是这样的,为了问问题才弄了这样一个代码。
echo $obj->authors[0]->firstName
这样搞过不显示东西,不过这段代码确实可以,我再查查自己的。谢谢!
  • 打赏
  • 举报
回复
SysTem128 2008-04-16

<?php
$jsonData = '{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
} ';
$obj = json_decode($jsonData);
var_export($obj->authors[0]->firstName);
/**
* 'Isaac'
*/
?>
  • 打赏
  • 举报
回复
相关推荐
发帖
基础编程

2.1w+

社区成员

从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
帖子事件
创建了帖子
2008-04-16 04:01
社区公告
暂无公告