/**
* @objective: Compare two json object string.
* @param: @para1: stdClass Object only, @para2: stdClass Object only, @para3: str default val is JSON, can pass the array.
* @return: Returns the diffrence value, return type based on @para3.
**/

function get_json_diff($array1, $array2, $type='JSON'){

global $differenceArray;

foreach($array1 as $k1 => $val) {

$array1_val = $array1->$k1;
$array2_val = $array2->$k1;

$count = count((array)$val);

if($count == 1){
if($array1_val != $array2_val){
$differenceArray[$k1]['field'] = $k1;
$differenceArray[$k1]['old_val'] = $array1_val;
$differenceArray[$k1]['new_val'] = $array2_val;
}
}
elseif($count > 1){
get_json_diff($array1_val, $array2_val, $type);
}

}

//echo json_encode($differenceArray);
if( $type =='JSON'){
echo json_encode($differenceArray);
}
else{
return $differenceArray;
}

}

Usage:

$jsonData1='{"key0":{"key00":"val00","key01":"val01","key02":"val02"},"key1":{"key11":"val11"}}';

$jsonData2='{"key0":{"key00":"val0","key01":"val1","key02":"val02"},"key1":{"key11":"val1"}}';
$array1 = json_decode($jsonData1);
$array2 = json_decode($jsonData2);

$result = get_json_diff($array1, $array2, 'array');

print_r($result);
Advertisements