用PHP合并两个JSON对象?

时间:2015-10-25 14:16:20

标签: php json

我有两个JSON对象,我希望它合并为一个JSON对象。我不希望JSON数据被覆盖。我希望数据合并

对象#1:(example1.json)

[{
    "title": "xx",        
    "releaseYear": "2014",        
},
{
    "title": "yy",       
    "releaseYear": "2015"        
}]

对象#2:(example2.json)

[{
    "title": "yy",       
    "releaseYear": "2017"

}]

这是我目前正在使用的 PHP文件

    <?php

    $jsonString = file_get_contents('example.json');
    $jsonString2 = file_get_contents('example2.json');   
    $data = json_decode($jsonString, true);
    $data2 = json_decode($jsonString2, true);      


    $op = array_merge_recursive( $data, $data2 );

    $resJson = json_encode($op);
    file_put_contents('example3.json', $resJson);   

收到的输出:(example3.json)

[  
   {  
      "title":"xx",
      "releaseYear":"2014"
   },
   {  
      "title":"yy",
      "releaseYear":"2015"
   },
   {  
      "title":"yy",
      "releaseYear":"2017"
   }
]    

必填项:

[{
    "title": "xx",        
    "releaseYear": "2014"        
},
{
    "title": "yy",       
    "releaseYear": "2017"        
}]

解决方案赞赏。我是Stackoverflow的新手,很遗憾我的格式错误,如果有的话。在此先感谢:)

1 个答案:

答案 0 :(得分:1)

许多可能的解决方案。一个例子:

<?php
$data = json_decode('[{"title": "xx","releaseYear": "2014"},{"title": "yy","releaseYear": "2015"}]', true);
$data2 = json_decode('[{"title": "yy","releaseYear": "2017"}]', true);

$data = foo($data, 'title');
$data = foo($data2, 'title', $data);
$data = array_values($data);
var_export($data);

function foo($src, $prop, $target=array()) {
    foreach($src as $o) {
        $target[ $o[$prop] ] = $o;
    }
    return $target;
}