hdeh hdeh - 4 months ago 14
JSON Question

JSON PHP array decode - Access specific data

I can't find out how to echo "tags" in this JSON data.

{"totalHits":26,"hits":[{"previewHeight":92,"tags":"sunflower, sunflower field, flora"}]};


I can echo "totalHits", by using this:

$json = file_get_contents($url);
$obj = json_decode($json);
echo $obj->totalHits; // 26

Answer

I would highly recommend using print_r to make it easier for you to trace the array

The output of print_r($obj);

stdClass Object
(
    [totalHits] => 26
    [hits] => Array
        (
            [0] => stdClass Object
                (
                    [previewHeight] => 92
                    [tags] => sunflower, sunflower field, flora
                )

        )

)

So your object can be accessed like this

echo $obj->hits[0]->tags;
Comments