Php 如何在两个JSON之间识别不同的数组

Php 如何在两个JSON之间识别不同的数组,php,Php,关于比较两个数组,我发现了不同的答案,但在我的案例中没有一个是有效的。我有两个json:保存旧值的Old.json和保存新值的New.json。我只想在Old.json中保存new.json中没有的新内容 OLD.JSON { "jogos-da-copa": [ "/videos/291856.html", "/videos/291830.html", "/videos/291792.html", "/videos/291

关于比较两个数组,我发现了不同的答案,但在我的案例中没有一个是有效的。我有两个json:保存旧值的Old.json和保存新值的New.json。我只想在Old.json中保存new.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);
从文档:

将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);

请使用下面的函数并将新旧数组传递给参数

$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);

这样它也不起作用,它返回所有的值,而不仅仅是差值