如何识别两个jsons之间的不同数组

时间:2018-05-10 03:54:10

标签: php

我找到了关于比较两个数组的不同答案,但在我的情况下没有一个工作。我有两个Jsons,Old.json保存旧值,New.json保存新值。我只想在Old中保存New.json中的新功能,而我在Old.json中还没有这个功能

OLD.JSON

{
    "jogos-da-copa": [
        "/videos/291856.html",
        "/videos/291830.html",
        "/videos/291792.html",
        "/videos/291759.html",
        "/videos/291720.html",
        "/videos/291705.html"
    ],
    "apresentacao": [
        "/videos/2926328.html",
        "/videos/67.html",
        "/videos/36.html",
        "/videos/3.html"
    ]
}

NEW.JSON

{
    "jogos-da-copa": [
        "/videos/291887.html",
        "/videos/291856.html",
        "/videos/291830.html",
        "/videos/291792.html",
        "/videos/291759.html",
        "/videos/291720.html",
        "/videos/291705.html"
    ],
    "apresentacao": [
        "/videos/2926385.html",
        "/videos/2926328.html",
        "/videos/67.html",
        "/videos/36.html",
        "/videos/3.html"
    ]
}

我使用了这段代码,但没有显示差异

$old1 = json_decode(file_get_contents('old.json'), true);
$new2 = json_decode(file_get_contents('new.json'), true);
$test = [];

foreach ($old1 as $key1 => $olds1) {

    foreach ($new2 as $key2 => $news2 ) {

    $test[] = array_diff($olds1, $news2);

    }

}

var_dump($test);

2 个答案:

答案 0 :(得分:1)

请使用以下功能并将旧的和新的数组传递给参数

$old = json_decode($old_json, true);
$new = json_decode($new_json, true);

$array_keys = array_keys( array_merge( $old, $new));

$dif_array = array();
foreach($array_keys as $key)
{
    if(array_key_exists($key, $old) && array_diff($new[$key], $old[$key])){
        $dif_array[$key] = array_diff($new[$key], $old[$key]);
    } else {
        $dif_array[$key] = $new[$key];
    }
}

$final_array = array_merge_recursive($old, $dif_array);

答案 1 :(得分:0)

来自array_diff docs:

将array1与一个或多个其他数组进行比较,并返回array1中任何其他数组中不存在的值。

在您的情况下,新数组包含旧数组中的所有值。要获取所有新值的列表,您需要切换参数:

$old1 = json_decode(file_get_contents('old.json'), true);
$new2 = json_decode(file_get_contents('new.json'), true);
$test = [];

foreach ($old1 as $key1 => $olds1) {

    foreach ($new2 as $key2 => $news2 ) {
        $test[] = array_diff($news2, $olds1);
    }

}

var_dump($test);