Merge and overwrite the json file where the ID matches, in PHP

advertisements

I need to merge json files, and overwrite when id's match, but it's not overwriting. My PHP is like so:

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[id] = array(
    'id' => $id,
    'url' => $url,
    'likes' => $likes,
    'date_shot' => $date_shot,
    $tags = implode(', ', $image['tags']);
);
    };

    $user_array = array_merge($values, $user_array);
    file_put_contents('myfile.json', json_encode($user_array, JSON_FORCE_OBJECT));

Resulting JSON is like so:

{
123_456: {
  id: "123_456",
  url: "photo1.jpg",
  likes: 22,
  date_shot: "Feb 20, 2015",
  tags: "tag1, tag2, tag3"
  },
123_457: {
  id: "123_457",
  url: "//photo2.jpg",
  likes: 20,
  date_shot: "Feb 20, 2015",
  tags: "tag1, tag5"
},...

I expected this to use the [$id] as a key, and overwrite the whole sub-array when it matched, but doesn't... It does keep adding more and more files to the file like I want it to, and it also avoids duplicate records as needed, but it just won't update an existing record.


You need to swap the arguments in array_merge like so:

$user_array = array_merge($user_array, $values);