php return difference of multidimensional arrays code example

Example: multidimensional array difference in php

function array_diff_assoc_recursive($array1, $array2) {
    $difference=array();
    foreach($array1 as $key => $value) {
        if( is_array($value) ) {
            if( !isset($array2[$key]) || !is_array($array2[$key]) ) {
                $difference[$key] = $value;
            } else {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if( !empty($new_diff) )
                    $difference[$key] = $new_diff;
            }
        } else if( !array_key_exists($key,$array2) || $array2[$key] !== $value ) {
            $difference[$key] = $value;
        }
    }
    return $difference;
}
//----------------------
$changes = array();
if ($result= array_diff_assoc_recursive($new_value,$old_value)) {
		$new  = array();
		
		foreach ($result as $key => $value) {
			$new[$key] =  $value;
		}
		// indicate your UNIQUE ID you can use this when you want know which row you wanted to update in database 
		$new['ID'] = $new_value['ID'];
		$changes[] = $new	;
}

print_r($changes);

Tags:

Php Example