Search code examples
phparraysjsonforeachinstagram-api

write the results of foreach loop to json with php


I am new to PHP and JSON, and am trying to write some data (that I grabbed from the Instagram API) to a json file. I know I've successfully decoded and grabbed the arrays from Instagram in a foreach() loop, because I can echo them out, but I can't seem to write them to json properly. When I do, I just get a single array, as opposed to a collection of them... here is my code:

foreach($instagram_array['data'] as $key => $image){
    $id = $image['id'];
    $url    = $image['images']['standard_resolution']['url'];
    $date_shot = date('M d, Y', $image['created_time']);
    $likes = $image['likes']['count'];
    };

//I've tried wrapping this below in a foreach loop as well, but without success
$values = array(
    'id' => $id,
    'url' => $url,
    'likes' => $likes,
    'date_shot' => $date_shot,
);

    file_put_contents('mydata.json', json_encode($values, JSON_FORCE_OBJECT)); // I wondered if force_object was the problem, but same result without it...

What I get is this, just once (the last in the loop):

{
id: "123_456",
url: "http://whatever.jpg",
likes: 5,
date_shot: "Jan 19, 2015"
}

When I am hoping to get (I think) is something more like this (the whole loop):

{
0: {
  id: "123_456",
  url: "http://whatever.jpg",
  likes: 5,
  date_shot: "Jan 19, 2015"
  }
1: {
  id: "123_457",
  url: "http://whatever2.jpg",
  likes: 10,
  date_shot: "Jan 21, 2015"
  }
2: {...}
}...

Ultimately the goal will be to merge this json file with updated version of itself, as a growing file, in case that makes a difference with how best to approach writing to json in the first place...


Solution

  • Your problem appears to be that you are creating individual arrays and writing them to a file, instead of creating a big "array of arrays" and then writing that to the file.

    Try this line instead:

    $values[] = ...
    

    The square brackets after $values means $values will become a multidimensional array.

    It should be moved inside your foreach loop, so the full code will now look like this:

    foreach($instagram_array['data'] as $key => $image){
        $id = $image['id'];
        $url    = $image['images']['standard_resolution']['url'];
        $date_shot = date('M d, Y', $image['created_time']);
        $likes = $image['likes']['count'];
    
        $values[] = array(
            'id' => $id,
            'url' => $url,
            'likes' => $likes,
            'date_shot' => $date_shot,
        );
    );
    
    file_put_contents('mydata.json', json_encode($values, JSON_FORCE_OBJECT));