1
$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"}

1
  • array_diff(json_decode($json_str1), json_decode($json_str2)) doesn't work? Commented Nov 30, 2019 at 11:46

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.