如何将两个JSON文件合并为一个

时间:2014-06-26 21:20:48

标签: php json

我有两个json文件名为:users.json和users_custom.json,我是使用php从mysql数据库创建的。 users.json文件看起来像:

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

和users_custom.json文件如下所示:

[{
    "user_id" : "1",
    "Name" : "Mr. A Modified",
    "email" : "someone@gmail.com"
},
{
    "user_id" : "2",
    "Name" : "Mr. B",
    "address" : "some address"
}]

所以,在users_custom.json文件中,我修改了一些字段并添加了一些新字段。现在,我想将users_custom.json与users.json文件合并到users_final.json文件中。最后,users_final文件应如下所示:

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

最后,我将把users_final.json文件导入MongoDB数据库。任何想法或示例代码将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:1)

这应该相当简单,获取两个文件的内容,解码它们,相应地循环它们,如果用户id匹配,合并它们,在该过程完成后,编码结果,然后写入文件。例如:

// $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" : "someone@gmail.com"},{ "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