Divesh Choudhary
Divesh Choudhary

Reputation: 45

Difference between two JSON strings in php and remove duplicate?

$json_str1 = '[{"13:00":"1"},{"14:00":"1"},{"15:30":"1"},{"16:30":"1"},{"1:00":"1"}]';
$json_str2 = '[{"13:00":"1"},{"14:00":"1"},{"15:30":"1"},{"12:30":"1"}]';

These are two JSON strings and I want the result like difference between them like {"1:00":"1"} and one more {"12:30":"1"}

Upvotes: 1

Views: 298

Answers (1)

Aksen P
Aksen P

Reputation: 4599

The solution of this has a many aspects, cause there's 3 different values:

{"16:30":"1"},{"1:00":"1"}
{"12:30":"1"}

Firstly, you can convert your JSON string into array with json_decode($str,true):

json_decode($json_str1, true);
json_decode($json_str2, true);

Outputs like:

Array
(
    [0] => Array
        (
            [13:00] => 1
        )
...

Then create combined array with values like JSON object elements with foreach loop:

$str1 = []; 
foreach($data1 as $row){
    $str1[] = json_encode($row);
}

Outputs like:

Array
(
    [0] => {"13:00":"1"}
    [1] => {"14:00":"1"}
    [2] => {"15:30":"1"}
    [3] => {"16:30":"1"}
    [4] => {"1:00":"1"}
)
...

Then you can find the difference between this two arrays, but, you need to do it in both ways (compare $array1 with $array2 and $array2 with $array1):

$dif1 = array_diff($str1, $str2);
$dif2 = array_diff($str2, $str1);

Outputs:

Array
(
    [3] => {"16:30":"1"}
    [4] => {"1:00":"1"}
)
Array
(
    [3] => {"12:30":"1"}
)

Finally you can merge the result with:

$fin = array_merge($dif1, $dif2);

Outputs:

Array
(
    [0] => {"16:30":"1"}
    [1] => {"1:00":"1"}
    [2] => {"12:30":"1"}
)

All of this you can put in a separate function like:

function getDifference2JSONstrings($jsonStr1, $jsonStr2){
    $data1 = json_decode($jsonStr1, true);
    $data2 = json_decode($jsonStr2, true);

    $str1 = [];
    $str2 = [];

    foreach($data1 as $row){
        $str1[] = json_encode($row);
    }

    foreach($data2 as $row){
        $str2[] = json_encode($row);
    }

  return array_merge(array_diff($str1, $str2), array_diff($str2, $str1));
} 

$res = getDifference2JSONstrings($json_str1, $json_str2);

print_r($res);

Outputs an array:

Array
(
    [0] => {"16:30":"1"}
    [1] => {"1:00":"1"}
    [2] => {"12:30":"1"}
)

Demo

Upvotes: 1

Related Questions