JSON Parse

Hey all, kind of a first timer with JSON parsing and was wondering how I could parse this JSON and select the image URL based on the size value. Thanks ahead of time.


"media": {
                        "photos": {
                            "photo": [
                                {
                                    "@size": "x",
                                    "$t": "http://photos.petfinder.com/photos/US/FL/FL286/25768801/FL286.25768801-1-x.jpg",
                                    "@id": "1"
                                },
                                {
                                    "@size": "fpm",
                                    "$t": "http://photos.petfinder.com/photos/US/FL/FL286/25768801/FL286.25768801-1-fpm.jpg",
                                    "@id": "1"
                                },
                                {
                                    "@size": "pn",
                                    "$t": "http://photos.petfinder.com/photos/US/FL/FL286/25768801/FL286.25768801-1-pn.jpg",
                                    "@id": "1"
                                },
                                {
                                    "@size": "pnt",
                                    "$t": "http://photos.petfinder.com/photos/US/FL/FL286/25768801/FL286.25768801-1-pnt.jpg",
                                    "@id": "1"
                                },
                                {
                                    "@size": "t",
                                    "$t": "http://photos.petfinder.com/photos/US/FL/FL286/25768801/FL286.25768801-1-t.jpg",
                                    "@id": "1"
                                }
                            ]
                        }

Use [fphp]json_decode[/fphp] with the second parameter set to true to decode the JSON into an associative array and then loop that array like you would any other array.

Suppose you’re looking for size ‘fpm’, then it would be


$array = json_decode($json, true);

$url = '';
foreach ($array['media']['photos']['photo'] as $photo)
{
    if ($photo['size'] === 'fpm')
    {
        $url = $photo['$t'];
    }
}
if ($url === '')
{
    // no photo found of size 'fpm'
}