在PHP中合并两个具有公共字段值的json文件

我已经用PHP生成了两个json文件。一,输出如下。即/json1.json


{

   "Zipcode":"22581",

   "City":"",

   "Primary State":"Maryland",

   "Common Field":"49969",

   "County":"Something"

}

第二个输出如下。即 /json2.json


{

    "Common Field":"49969",

    "Option 1":"Y",

    "Option 2":"",

    "Option 3":""

}

我想找到一种方法来合并它们,理想情况下是使用PHP,这样它们的输出如下:


{

    "Zipcode":"22581",

    "City":"",

    "Primary State":"Maryland",

    "Common Field": {

       "Common Field":"49969",

       "Option 1":"Y",

       "Option 2":"",

       "Option 3":""

    },

    "County":"Something"

},

更新,以下两个发布者建议的方法不起作用:不管是否在最后使用true,这只会在每个条目旁边输出带有数字的json。并且不会通过公共字段将两个json文件与所需的格式连接起来,如上所述。


$json1 = json_decode(file_get_contents('json1.json'),true);

$json2 = json_decode(file_get_contents('json2.json'),true);


$json1['Common Field'] = $json2;


echo json_encode($json1, JSON_PRETTY_PRINT);

这只是从/输出每个条目json1.json:


"0": { "Zipcode": "20101", "City": "", "Primary State": "Virginia", "Common Field": "49530", "County": "Loudoun" }


萧十郎
浏览 211回答 3
3回答

米脂

您可以使用array_walk以获得所需的结果$json1 = '{ "Zipcode":"22581", "City":"", "Primary State":"Maryland", "Common Field":"49969", "County":"Something"}';$json2 = '{  "Common Field":"49969",  "Option 1":"Y",  "Option 2":"",  "Option 3":""}';$json1Array = json_decode($json1, true);$json2Array = json_decode($json2, true);array_walk($json1Array, function($value, $key) use (&$json1Array, $json2Array){  $json1Array['Common Field'] = $json2Array;});$result = json_encode($json1Array);

慕的地10843

试试这个:$json1 = (array)json_decode(file_get_contents('json1.json'));$json2 = (array)json_decode(file_get_contents('json2.json'));$json1['Common Field'] = $json2;echo json_encode($json1, JSON_PRETTY_PRINT);输出:{    "Zipcode": "22581",    "City": "",    "Primary State": "Maryland",    "Common Field": {        "Common Field": "49969",        "Option 1": "Y",        "Option 2": "",        "Option 3": ""    },    "County": "Something"}
打开App,查看更多内容
随时随地看视频慕课网APP