2013-04-17 43 views
0

我有两个数组,我试图找出两者之间的差异/相似之处。PHP Array键和值的比较

这里是数组:

[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" 
    } 

这里是第二阵列:

 [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" 
     } 

注意,第二阵列(780)中的键不与第一数组中的存在。另外请注意,数组2(ID 782)的“状态”现在处于“激活”状态,但最初处于已删除状态。

该项目的总体目标是比较两个数组,找到差异,然后将这些差异放在数组或字符串中,然后通过电子邮件发送差异。这是我到目前为止所尝试的:

$Deleted[] = array_diff_assoc($myarrayOld, $myarrayNew); 
$Added[] = array_diff_assoc($myarrayNew, $myarrayOld); 

这将拾取数组键之间的更改,但不是数组的状态键之间的更改。

回答

1

使用一个递归函数像这样

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; 
} 

参考:PHP documentation

0

这里有一个比较2个数组的小代码。

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'; 
}