hasib32
hasib32

Reputation: 835

How to merge two JSON files into one

I have two json files named: users.json and users_custom.json which I created from mysql database using php. users.json file looks like:

[{
    "user_id" : "1",
    "Name" : "Mr. A",
    "phone" : "12345"
},
{
    "user_id" : "2",
    "Name" : "Mr. B",
    "phone" : "23456"
}]

and users_custom.json file looks like:

[{
    "user_id" : "1",
    "Name" : "Mr. A Modified",
    "email" : "[email protected]"
},
{
    "user_id" : "2",
    "Name" : "Mr. B",
    "address" : "some address"
}]

so, in users_custom.json file I have modified some fields and also added some new fields. Now, I want to merge users_custom.json over users.json file into users_final.json file. At the end users_final file should looks like this:

[{
    "user_id" : "1",
    "Name" : "Mr. A Modified",
    "phone" : "12345"
    "email" : "[email protected]"
},
{
    "user_id" : "2",
    "Name" : "Mr. B",
    "phone" : "23456"
    "address" : "some address"
}]

At the end I will import the users_final.json file to MongoDB database. Any idea or example code will be greatly appreciated. Thanks in advance.

Upvotes: 1

Views: 3530

Answers (1)

user1978142
user1978142

Reputation: 7948

This should be fairly straightforward, get contents of both files, decode them both, loop them accordingly, if the user id's match, merge them, after that process is complete, encode the resultant, then write the file. Example:

// $contents_of_users = file_get_contents('users.json');
$contents_of_users = '[{ "user_id" : "1", "Name" : "Mr. A", "phone" : "12345"},{ "user_id" : "2", "Name" : "Mr. B", "phone" : "23456"}]';
// $contents_of_users_custom = file_get_contents('users_custom.json');
$contents_of_users_custom = '[{ "user_id" : "1", "Name" : "Mr. A Modified", "email" : "[email protected]"},{ "user_id" : "2", "Name" : "Mr. B", "address" : "some address"}]';

$data_user = json_decode($contents_of_users, true);
$data_user_custom = json_decode($contents_of_users_custom, true);
$final = $data_user;
foreach($final as $key => &$user) {
    foreach($data_user_custom as $user_custom) {
        if($user['user_id'] == $user_custom['user_id']) {
            $user = array_merge($user, $user_custom);
        }
    }
}

$final = json_encode($final, JSON_PRETTY_PRINT);
echo '<pre>';
print_r($final);

file_put_contents('users_final.json', $final);

Sample Output

Upvotes: 1

Related Questions