PHP JSON数据预示着问题

时间:2011-01-15 15:40:20

标签: php json

我想制作一个PHP JSON数据,但我遇到了一些问题。第一:我不能得到properties部分。其次,alawys显示错误:echo '<div class="image">... Fatal error: Cannot use object of type stdClass as array in ... 这是json数据:

[
    {
        "post_id": "504464716_189878284371815",
        "message": "\"Happy Birthday to You\" \"Happy Birthday to Mama\"",
        "attachment": {
            "media": [
                {
                    "href": "http:\/\/www.facebook.com\/photo.php?fbid=493710409716&set=a.453260184716.254996.504464716",
                    "alt": "",
                    "type": "photo",
                    "src": "http:\/\/photos-f.ak.fbcdn.net\/hphotos-ak-snc4\/hs049.snc4\/34793_493710409716_504464716_5821684_2056840_s.jpg",
                    "photo": {
                        "aid": "2166659457206182932",
                        "pid": "2166659457211749620",
                        "owner": 504464716,
                        "index": 24,
                        "width": 225,
                        "height": 225
                    }
                }
            ],
            "name": "Wall Photos",
            "href": "http:\/\/www.facebook.com\/album.php?aid=254996&id=504464716",
            "caption": "\"Happy Birthday to You\" \"Happy Birthday to Mama\"",
            "description": "",
            "properties": [
                {
                    "name": "By",
                    "text": "Suman Acharya",
                    "href": "http:\/\/www.facebook.com\/profile.php?id=504464716"
                }
            ],
            "icon": "http:\/\/static.ak.fbcdn.net\/rsrc.php\/yD\/r\/aS8ecmYRys0.gif",
            "fb_object_type": "album",
            "fb_object_id": "2166659457206182932"
        },
        "action_links": null,
        "privacy": {
            "value": ""
        }
    },
...
]

这是我的php代码:

foreach ($data as $result) { 
echo '<div class="title"><a href="'.htmlspecialchars($result->link).'">'.htmlspecialchars($result->message).'<br />'.htmlspecialchars($result->description).'<br />'.htmlspecialchars($result->caption).'</a><br />';
if(!empty($result->attachment->properties[0]->text)){
    foreach ($result->attachment->properties[0] as $properties) { 
echo htmlspecialchars($properties->name).'<br /><a href="'.htmlspecialchars($properties->href).'">'.htmlspecialchars($properties->text).'</a></div>'; 
    }
}
if(!empty($result->attachment->media)){
echo '<div class="image"><a href="'.htmlspecialchars($result->attachment->media[0]->href).'"><img src="'.htmlspecialchars($result->attachment->media[0]->src).'" /><br>'.htmlspecialchars($result->attachment->media[0]->type).'</a></div>'; 
}
}

2 个答案:

答案 0 :(得分:1)

如果我是你,我只会强制解码到true的关联数组作为json_decode的第二个arg。如果您不想或不想这样做,请尝试像这样访问它:

$result->attachment->media->{0}->href

答案 1 :(得分:0)

使用json_decode($the_data, true);代替json_decode($the_data);,这样会返回一个关联数组,而不是StdClass