以前关于SO的类似问题给了我线索,但由于我的情况下json格式,我有问题。
我使用file_get_content($url)
解析$ url的内容。
这给了我结果json string:
{
"http://ec.x.x.x.xcompute-1.amazonaws.com/": {
"comments": {
"data": [
{
"id": "239_320054",
"from": {
"name": "x",
"id": "46353"
},
"message": "testing",
"can_remove": false,
"created_time": "2013-10-02T10:47:30+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "181319910",
"from": {
"name": "y",
"id": "166353"
},
"message": "hi",
"can_remove": false,
"created_time": "2013-10-02T07:30:00+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "MQ==",
"before": "Mg=="
}
}
}
}
}
我的问题:如何从json字符串上解析单个字符串中的所有消息?
从我从其他SO回答和参考中获得的线索,我可以做到:
$json = "above_json_result";
$obj = json_decode($json);
print $obj->{'message'};
这是我的整个代码,它没有给出任何结果:
<html>
<head>
<script type="text/javascript">
function show() {
alert("hi");
var json = '{
"http://x.x.x.x.compute-1.amazonaws.com/": {
"comments": {
"data": [
{
"id": "f434343",
"from": {
"name": "x",
"id": "1666353"
},
"message": "testing",
"can_remove": false,
"created_time": "2013-10-02T10:47:30+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "181596_319910",
"from": {
"name": "y",
"id": "10546353"
},
"message": "hi",
"can_remove": false,
"created_time": "2013-10-02T07:30:00+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "MQ==",
"before": "Mg=="
}
}
}
}
}';
var obj = json_decode($json);
alert(obj->{'message'});
}
</script>
</head>
<body onload="show()">
<button type="submit" value="click " onclick="show()"> button </button>
</body>
</html>
答案 0 :(得分:1)
这可以帮到你。 (编号为foreach循环中的级别)
foreach ($obj as $one) {
foreach ($one as $two) {
foreach($two as $three) {
foreach($three as $four) {
print $four->message . '<br />';
}
}
}
}
答案 1 :(得分:1)
你用javascript编写php,但你不包含php标签
function show() {
alert("hi");
<?php
$json = '{
"http://x.x.x.x.compute-1.amazonaws.com/": {
"comments": {
"data": [
{
"id": "f434343",
"from": {
"name": "x",
"id": "1666353"
},
"message": "testing",
"can_remove": false,
"created_time": "2013-10-02T10:47:30+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "181596_319910",
"from": {
"name": "y",
"id": "10546353"
},
"message": "hi",
"can_remove": false,
"created_time": "2013-10-02T07:30:00+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "MQ==",
"before": "Mg=="
}
}
}
}
}';
$obj = json_decode($json);
echo " alert(" . $obj->{'message'} . ");";
?>
}
此外,您的JSON对象不包含作为顶级邮件,邮件是嵌套的,因此您需要使用:
$data = $obj->{'http://x.x.x.x.compute-1.amazonaws.com/'}->comments->data;
foreach ($data as $obj) {
echo " alert(" . $obj->message . ");";
}