【问题标题】:Difference between two JSON strings in php and remove duplicate?php中两个JSON字符串之间的区别并删除重复项?
【发布时间】:2020-03-25 16:51:25
【问题描述】:
$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"}

【问题讨论】:

  • array_diff(json_decode($json_str1), json_decode($json_str2)) 不起作用?

标签: php arrays json associative-array difference


【解决方案1】:

这个解决方案有很多方面,因为有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

【讨论】:

    猜你喜欢
    • 2013-02-04
    • 2011-04-14
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    相关资源
    最近更新 更多