0

我有两个数组,我试图找出两者之间的差异/相似之处。

这是数组:

   [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 ) 中的键在第一个数组中不存在。另请注意,第二个数组(id 782)的“状态”现在为“活动”,但最初处于已删除状态。

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

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

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

4

2 回答 2

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 文档

于 2013-04-17T14:37:30.763 回答
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';
}
于 2013-04-17T14:32:07.720 回答