Bruno Andrade
Bruno Andrade

Reputation: 595

How to identify different arrays between two jsons

I found different answers about comparing two arrays but none worked in my case. I have two Jsons an Old.json with old values saved and New.json with new values to be saved. I just want to save in Old what's new in New.json that I do not already have in 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"
    ]
}

I used this code but it is not displaying the differences

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

Upvotes: 1

Views: 40

Answers (2)

Jaydp
Jaydp

Reputation: 1039

Please use below function and pass your old and new array to the argument

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

Upvotes: 1

Karolis
Karolis

Reputation: 2618

From array_diff docs:

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

In your case, the new array contains all the values from the old array. To get a list of all the new values, you need to switch your arguments around:

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

Upvotes: 0

Related Questions