我需要从这个对象数组中提取数据
{
"data": [
{
"id": "136104923104306",
"from": {
"name": "GetWith.It",
"category": "Website",
"id": "136132969751208"
},
"message": "Do u know y **LOVE IS BLIND**\nbcoz..\n''ur mom started to love u before seeing ur face''....!",
"updated_time": "2010-10-05T13:41:42+0000",
"comments": {
"data": [
{
"id": "136104923104306_1075253",
"from": {
"name": "Hressence Ec",
"id": "1464305271"
},
"message": "this I would agree..love is surely blind..",
"created_time": "2010-10-12T01:40:47+0000",
}
]
}
}
我目前的代码:
$data=json_decode(file_get_contents('https://myurl/where/this/data/is'));
foreach($data as $dts){
echo "$dts->message";
};
我需要提取评论.. 当我尝试
时foreach($data->comments->data as $dts){
echo "$dts->message";
};
它返回null! 请帮忙
答案 0 :(得分:1)
您的$data
实际上是一个带有 data 属性的对象,该属性是一个包含另一个对象的数组,其中包含您正在寻找的 comments 对象。所以:
foreach ($data->data as $item) {
foreach ($item->comments->data as $comment) {
echo $comment->message;
}
}
答案 1 :(得分:0)
我建议你把它转换成一个关联数组:
$data=json_decode(file_get_contents('https://myurl/where/this/data/is'), true);
并查看结构。
我认为你的循环必须如下:
foreach($data['data'] as $dts) {
echo $dts['message'];
}
更新虽然我能够修复JSON(至少现在似乎很好)json_decode
仍然会返回null
。没有线索的方式。首先确保您的JSON字符串有效!