php中两个JSON字符串之间的区别,并删除重复项?

问题描述 投票:0回答: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"}]';

这是两个json字符串,我希望结果像这两个的区别是{“ 1:00”:“ 1”}和另一个区别{“ 12:30”:“ 1”}

arrays json associative-array difference
1个回答
0
投票

此解决方案有很多方面,导致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对象元素之类的值的组合数组:

$str2 = []; 
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

© www.soinside.com 2019 - 2024. All rights reserved.