简体   繁体   中英

How do I merge the output of a for loop into a single array or JSON file in PHP?

I'm trying to get the counts of photos by location but when I loop through various locations the output comes out as separate arrays. I would like it all to come out as a single array to then be converted to JSON.

 <?php

    $gURL= "URL";
    $pullstring = file_get_contents($gURL);
    $jsonish = json_decode($pullstring, TRUE);
    $feature= $jsonish['features'];
    $arrlength = count($feature);

    for($x = 0; $x < 10; $x++)
    {

        $Inames= str_replace(" ", "+", $feature[$x]['properties']['name']);
        $lats= $feature[$x]['geometry']['coordinates'][1];
        $longs= $feature[$x]['geometry']['coordinates'][0];
        $ID= $feature[$x]['properties']['osm_id'];
        $numba='XXXXXXXXXXXX';  

        $instagram_URL = 'https://api.instagram.com/v1/media/search?lat='.$lats.'&lng='.$longs.'&distance=10&client_id='.$numba;
        $instagram_json = file_get_contents($instagram_URL);
        $instagram_array = json_decode($instagram_json, TRUE);
        $instagram_var= array('ID'=>$ID,'name'=>$Inames,'photos'=>count($instagram_array['data']));
        //print_r ($instagram_var);
    };

    ?>

Output:

  Array (
[ID] => 1
[name] => 1905
[photos] => 15
) Array (
[ID] => 2
[name] => 15+ria
[photos] => 19
) Array (
[ID] => 3
[name] => 18th+Amendment
[photos] => 19
) Array (
[ID] => 4
[name] => 1920dc
[photos] => 15
) Array (
[ID] => 5
[name] => 19th
[photos] => 19
) Array (
[ID] => 6
[name] => 2+Birds+1+Stone
[photos] => 6
) Array (
[ID] => 7
[name] => 201+Bar
[photos] => 7
) Array (
[ID] => 8
[name] => 30+Degrees+Lounge
[photos] => 19
) Array (
[ID] => 9
[name] => 51st+State
[photos] => 7
) Array (
[ID] => 10
[name] => 8+x+10+Club
[photos] => 19
)

Make your $instagram_var a two-dimensional array.

$instagram_var = Array();
for ($...) { // your loop
     /* ... */
     $instagram_var[] = array('ID'=>$ID,'name'=>$Inames,'photos'=>count($instagram_array['data']));
}

Afterwards you can access each individual Array with $instagram_var[0] , $instagram_var[1] ... and its inner values with $instagram_var[0]['ID'] etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM