简体   繁体   中英

merge and overwrite json file where id's match, in PHP

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.

您需要像这样交换array_merge中的参数:

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

I think that part of array_merge docs should help you:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

And you have numeric keys. So you can merge it manually or make your keys strings.

Also if you only need to replace elements, not append ones you should take a look on array_replace function

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