The Codesee The Codesee - 6 months ago 10
JSON Question

Multiple JSON files using an array isn't working

I am trying to display data from multiple

JSON
files using an
array
.

When using the code below, only the data from the last file in the array is displayed. How do I ensure that the data from all the files in the array are displayed?

<?php
$homepage = array();
$homepage[] = "http://linktojson.com/1/";
$homepage[] = "http://linktojson.com/2/";
$homepage[] = "http://linktojson.com/3/";
$homepage[] = "http://linktojson.com/4/";
$homepage[] = "http://linktojson.com/5/";

foreach ($homepage as $homepage2) {
$data = json_decode(file_get_contents($homepage2, false));
}

foreach ($data->Content->Catalog as $each) {
echo $each->ID;
}
?>


If I change the order of the JSON files, still only the data from the last file in the array displays

Answer

You are overwriting $data with each iteration of your first foreach loop. If you move the second loop inside the first loop, you will see the IDs from each file.

foreach ($homepage as $homepage2) {
    $data = json_decode(file_get_contents($homepage2, false));
    foreach($data->Content->Catalog as $each){
        echo $each->ID;
    }
}