0

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"}]';
Umaiz Khan
  • 1,319
  • 3
  • 20
  • 66

3 Answers3

1

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

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
0

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.

maximkou
  • 5,252
  • 1
  • 20
  • 41
  • While this advice may actually work on the sample data provided, it is definitely not professional practice to manually craft a valid json string using string functions. Researchers -- you've been warned. – mickmackusa Sep 15 '20 at 03:49
0

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);
Watts Epherson
  • 692
  • 5
  • 9
  • I would simplify to this: `$data = []; foreach (["cache.json", "cache2.json"] as $f) { $data = array_merge($data, json_decode(file_get_contents($f), true)); } echo json_encode($data);` – mickmackusa Sep 15 '20 at 03:54