简体   繁体   中英

PHP Merge json files

I have 2 json file each file contain 500 arrays. i need to merge 2 files in 1 file so the result will be 1000 arrays. I have found code from stackoverflow but its not working its just showing me the file 1 data.

<?php

$a = file_get_contents ("cache.json");
$b = file_get_contents ("cache2.json");

$r = [];
foreach(json_decode($a, true) as $key => $array){
 $r[$key] = array_merge(json_decode($b, true)[$key],$array);
}
echo count($r);
?>

The json data look like this

$a = '[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"},{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]';
$b = '[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]';

Try array_merge with json_decode

 $r = array_merge(json_decode($a,true), json_decode($b,true));
 echo json_encode($r);

Working example: https://3v4l.org/J6iW3

Alternative solution, without decoding:

function concatJsonArrays(...$arrays) {
    $result = [];

    foreach ($arrays as $array) {
        $result[] = substr($array, 1, strlen($array) - 2);
    }

    return "[".implode(',', $result)."]";
}

// print result aray
echo concatJsonArrays($a, $b);

This solution must be better, if you have big json data or deep objects in json.

You can use array merge but I would suggest first ensuring the JSON code is valid AND the files exist before assuming json_decode will return an array. Otherwise, if you merge NULL or FALSE with an array, you end up with FALSE as the final result.

Imagine the first cache file exists, and the other one doesn't or one of them is broken and contains broken encoded JSON data.

With checks, at least you know you will always get an array with as much of the valid array data as possible or know when to report errors and one which file in one of the stages.

$data = Array();
foreach(Array("cache.json","cache2.json") as $f){
    $dc = Array();
    if($fc = file_get_contents($f)){
        if($dc = json_decode($fc,true)){
            $data = empty($data)?$dc:array_merge($data,$dc);
        }
    }
}

echo json_encode($data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM