这个解决方案有很多方面,因为有3个不同的值:
{"16:30":"1"},{"1:00":"1"}
{"12:30":"1"}
首先,您可以使用 json_decode($str,true) 将 JSON 字符串转换为数组:
json_decode($json_str1, true);
json_decode($json_str2, true);
输出如下:
Array
(
[0] => Array
(
[13:00] => 1
)
...
然后使用 foreach 循环创建具有 JSON 对象元素等值的组合数组:
$str1 = [];
foreach($data1 as $row){
$str1[] = json_encode($row);
}
输出如下:
Array
(
[0] => {"13:00":"1"}
[1] => {"14:00":"1"}
[2] => {"15:30":"1"}
[3] => {"16:30":"1"}
[4] => {"1:00":"1"}
)
...
然后你可以找到这两个数组之间的区别,但是,你需要用两种方式来做(比较$array1和$array2和$array2和$array1):
$dif1 = array_diff($str1, $str2);
$dif2 = array_diff($str2, $str1);
输出:
Array
(
[3] => {"16:30":"1"}
[4] => {"1:00":"1"}
)
Array
(
[3] => {"12:30":"1"}
)
最后你可以合并结果:
$fin = array_merge($dif1, $dif2);
输出:
Array
(
[0] => {"16:30":"1"}
[1] => {"1:00":"1"}
[2] => {"12:30":"1"}
)
所有这些你都可以放在一个单独的函数中,比如:
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);
输出一个数组:
Array
(
[0] => {"16:30":"1"}
[1] => {"1:00":"1"}
[2] => {"12:30":"1"}
)
Demo