Home > Mobile >  Compare Two JSON Objects and return the different value and key name
Compare Two JSON Objects and return the different value and key name

Time:07-20

i have two json objects

object1 = [{"acc_number":1001,"acc_name":"admin","acc_loc":"headquarters"}]

object2 = [{"acc_number":1001,"acc_name":"New Admin","acc_loc":"branch"}]

because the different are at acc_name and acc_loc (new and old), i want the result like below:

result = [{"key_name":"acc_name","old_value":"admin","new_value":"New Admin}, 
      {"key_name":"acc_loc","old_value":"headquarters","new_value":"branch}]

can someone help me how to reselove it with PHP? thank you.

CodePudding user response:

<?php
$one = json_decode(json_encode(array("acc_number" => 1001,"acc_name" => "admin","acc_loc" => "headquarters"), JSON_FORCE_OBJECT));
$two = json_decode(json_encode(array("acc_number" => 1001,"acc_name" => "New Admin","acc_loc" => "branch"), JSON_FORCE_OBJECT));
//print_r($one);
$results = array();
foreach ($one as $key => $value) {
$result = array();
  if($value != $two->$key) {
    $result['key_name'] = $key;
    $result['old_value'] = $value;
    $result['new_value'] = $two->$key;
    array_push($results, $result);
  }
}
print_r($results);

?>

output

Output:

Array
(
[0] => Array
    (
        [key_name] => acc_name
        [old_value] => admin
        [new_value] => New Admin
    )

[1] => Array
    (
        [key_name] => acc_loc
        [old_value] => headquarters
        [new_value] => branch
    )

)

  • Related