4

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

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

2
  • your json decode is returning associative arrays. So array_diff_assoc might help. Commented May 6, 2016 at 4:59
  • Awesome, that made it! Do you know if it's somehow possible to find out if anyone has changed their whitelist_name though? Commented May 6, 2016 at 5:02

1 Answer 1

6

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
    }
} 
Sign up to request clarification or add additional context in comments.

4 Comments

Awesome, that made it! Do you know if it's somehow possible to find out if anyone has changed their whitelist_name though?
To find changed values you will have to loop over array and compare it with the other to find out if they are same or not.
@MartinO I have updated my answer for finding out changed values
Glad to know it helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.