Martin O Martin O - 7 months ago 12
PHP Question

Comparing 2 json strings to find new entries

I am trying to compare 2 json strings with each other to find all new entries in the list.

Json 1: http://164.132.195.253/test/new.json

Json 2: http://164.132.195.253/test/last.json

This is how I am comparing them:

$json = json_decode(file_get_contents("new.json"), true);
$last_json = json_decode(file_get_contents("last.json"), true);
$difference = array_diff($json, $last_json);

print_r($difference);


I am expecting it to return an array with all new entries. However, I am just getting an empty array in return.

Any help would be appreciated!

Additional information:
I am also trying to compare the values of the arrays. This is how I'm trying to do that:

foreach($json["whitelist_name"] AS $json_key => $json_val) {
foreach($last_json["whitelist_name"] AS $last_json_key => $last_json_val) {
if($json["whitelist_name"] != $last_json["whitelist_name"]) {
echo $json["whitelist_name"];
}
}
}


However, it seems that $json["whitelist_name"] is undefined

Answer

array_diff_assoc is the way to get difference of associative arrays:

$json = json_decode(file_get_contents("new.json"), true);
$last_json = json_decode(file_get_contents("last.json"), true);
$difference = array_diff_assoc($json, $last_json);

print_r($difference); 

This small piece of code will find out if any whitelist_name is different in the new json than the old one

foreach($last_json as $key=>$value){
    if($value['whitelist_name'] != $json[$key]['whitelist_name']){
        // value is changed
    }else{
        // value is not changed
    }
}