Reputation: 11436
I have two arrays that I am trying to find the differences / similarities between the two.
Here is the arrays:
[781]=>
array(7) {
["Pri_ID"]=>
string(3) "781"
["Type"]=>
string(7) "Athlete"
["EntryDate"]=>
string(10) "2013-04-15"
["Status"]=>
string(6) "Active"
}
[782]=>
array(7) {
["Pri_ID"]=>
string(3) "782"
["EntryDate"]=>
string(10) "2013-04-15"
["Status"]=>
string(7) "Removed"
}
here is the second array:
[780]=>
array(7) {
["Pri_ID"]=>
string(3) "781"
["EntryDate"]=>
string(10) "2013-04-15"
["Status"]=>
string(7) "Removed"
}
[782]=>
array(7) {
["Pri_ID"]=>
string(3) "782"
["EntryDate"]=>
string(10) "2013-04-15"
["Status"]=>
string(7) "Active"
}
Notice that the key in the second array (780 ) does not exist in the first array. Also notice that the 'status' of array number two (id 782 )is now 'active' but was originally in a status of removed.
The overall goal of this project is to compare the two arrays, located any differences, then placed these differences in either and array or a string and email the differences. Here is what I have tried so far:
$Deleted[] = array_diff_assoc($myarrayOld, $myarrayNew);
$Added[] = array_diff_assoc($myarrayNew, $myarrayOld);
This will pick up the changes between the array keys, but not the statuskeys of the array.
Upvotes: 0
Views: 84
Reputation: 8415
Use an recursive function like this
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;
}
Reference: PHP documentation
Upvotes: 1
Reputation: 109
Here a small code to compare 2 arrays.
function compareAssociativeArrays($first_array, $second_array)
{
$result = array_diff_assoc($first_array, $second_array);
if(!empty($result))
{
//Arrays are different
//print_r($result); will return the difference as key => value pairs.
return FALSE;
}
else
{
//Arrays are same.
//print_r($result); returns empty array.
return TRUE;
}
}
//Usage:
$first = array(
'name' => 'Zoran',
'smart' => 'not really'
);
$second = array(
'smart' => 'not really',
'name' => 'Zoran'
);
if(compareAssociativeArrays($first, $second))
{
echo 'Arrays are same';
}
else
{
echo 'Arrays are different';
}
Upvotes: 0