PHP Json 文件合并

我需要将 json 文件合并到 1 个文件中。


我在 3 个文件中有这样的 json


{

    "count": 2077,

    "records": [

{

        "comm_date": "51529",

        "Certificate_Number": "31",

},

{

        "comm_date": "51529",

        "Certificate_Number": "31",

}

]} 

但是探针是因为我有计数和记录数组在这里所以它没有成功合并


<?php


$a1 = file_get_contents ("EngroClaims.json");

$a2 = file_get_contents ("EngroClaims2.json");


$a6 = file_get_contents ("SCB1Claims.json");

$a7 = file_get_contents ("TotalParcoClaims.json");

$a8 = file_get_contents ("SAPTClaims.json");


 $r = array_merge(json_decode($a1,true), json_decode($a2,true), json_decode($a6,true), json_decode($a7,true), json_decode($a8,true));


file_put_contents('conventional.json', json_encode($r));


?>

这是我的 php 代码,它工作正常。但我需要合并所有数组records


例子


第一个文件


{

    "count": 2,

    "records": [

{

        "comm_date": "1",

},

{

        "comm_date": "2",

}

]} 

第二个文件


{

    "count": 3,

    "records": [

{

        "comm_date": "1",

},

{

        "comm_date": "2",

},

{

        "comm_date": "3",

}

]} 

预期结果


{

    "count": 9, //this count value is not imprtant assume it will show 1

    "records": [

{

        "comm_date": "1",

},

{

        "comm_date": "2",

},

{

        "comm_date": "1",

},

{

        "comm_date": "2",

},

{

        "comm_date": "3",

}

]} 


慕勒3428872
浏览 244回答 2
2回答

九州编程

您可以使用这种方式;<?php$a1 = file_get_contents ("EngroClaims.json");$a2 = file_get_contents ("EngroClaims2.json");$a1 = json_decode($a1, true);$a2 = json_decode($a2, true);$count = $a1["count"] + $a2["count"];$data = array();$data["count"] = $count;foreach ($a1["records"] as $row) {&nbsp; &nbsp; $data["records"][] = $row;}foreach ($a2["records"] as $row) {&nbsp; &nbsp; $data["records"][] = $row;}echo json_encode($data);我发现了你的问题。去掉 json 中的逗号(代码中有解释)。$a1 = '{&nbsp; &nbsp; "count": 2077,&nbsp; &nbsp; "records": [{&nbsp; &nbsp; &nbsp; &nbsp; "comm_date": "51529",&nbsp; &nbsp; &nbsp; &nbsp; "Certificate_Number": "31", <--- THIS IS A PROBLEM},{&nbsp; &nbsp; &nbsp; &nbsp; "comm_date": "51529",&nbsp; &nbsp; &nbsp; &nbsp; "Certificate_Number": "31", <--- THIS IS A PROBLEM}]}';/* in order for this solution to work you need to delete that comma.&nbsp;&nbsp; &nbsp; Because there isn't a following data in the json so the comma should not be there */检查此链接; http://sandbox.onlinephpfunctions.com/code/8dfab10352cf4966c95eb599d2ed8644b24b49ab

繁星淼淼

如果不需要计数,可以使用 array_merge_recursive$r&nbsp;=&nbsp;array_merge_recursive(json_decode($a1,true),&nbsp;json_decode($a2,true),json_decode($a3,true)); echo&nbsp;json_encode($r);会给你结果{"count":[3,3,3],"records":[{"comm_date":"1"},{"comm_date":"2"},{"comm_date":"3"},{"comm_date":"1"},{"comm_date":"2"},{"comm_date":"3"},{"comm_date":"1"},{"comm_date":"2"},{"comm_date":"3"}]}
打开App,查看更多内容
随时随地看视频慕课网APP