比较2个数组

时间:2013-03-18 15:27:38

标签: php arrays

是否有一个函数来比较2个不同的关联数组,并返回更改?

例如

$age = array("Peter"=>"35","Ben"=>"37","Joe"=>"");
$age2 = array("Peter"=>"38","Ben"=>"37","Joe"=>"43");

返回

$return = array(
    "Peter"=>"Changed from 35 to 38",
    "Joe"=>"Changed from blank to 43"
);

4 个答案:

答案 0 :(得分:5)

array_diff可能会让你走上正确的道路。虽然它没有给出您正在寻找的确切输出,但它会显示两个数组之间的差异。

正如商标所指出的那样,array_diff_assoc可能会更有帮助,因为它维护了数组索引。

答案 1 :(得分:2)

如前所述,array_diff_assoc是您的出发点。其余的是为每个差异构建你的字符串:

function compareAge($age, $age2)
{
    $return = array();
    foreach(array_keys(array_diff_assoc($age, $age2)) as $diffKey) {
        $from = empty($age[$diffKey]) ? 'blank' : $age[$diffKey];
        $to = empty($age2[$diffKey]) ? 'blank' : $age2[$diffKey];
        $return[$diffKey] = "Changed from {$from} to {$to}";
    }
    return $return;
}

<强> working demo

答案 2 :(得分:1)

没有任何默认,我手上有一些时间:) http://codepad.org/2UtrPE3o

<?
$age = array("Peter"=>"35","Ben"=>"37","Joe"=>"");
$age2 = array("Peter"=>"38","Ben"=>"37","Joe"=>"43");

$result = array();
foreach($age as $key=>$val) {
  if (array_key_exists($key, $age2)) {
    if ($val!==$age2[$key])
      $result[$key] = 'Changed from '.(empty($val)?'blank':$val).' to '. (empty($age2[$key])?'blank':$age2[$key]);
  } else {
    $result[$key] = 'Changed from '.(empty($val)?'blank':$val).' to blank';
  }
}

foreach($age2 as $key=>$val) {
  if (!array_key_exists($key, $age)) {
    $result[$key] = 'Changed from blank to ' . $val;
  }
}

var_dump($result);
?>

答案 3 :(得分:0)

检查这个更有效的解决方案:

$age1   = array("Peter"=>"35","Ben"=>"37","Joe"=>"");
$age2   = array("Peter"=>"38","Ben"=>"37","Joe"=>"43");

$result = array_diff_assoc($age1, $age2);

$res    = array();
foreach($result as $key=>$val){
  $res[$key]  = "Changed from ".($val?$val:"Balnk")." to ".($age2[$key]?$age2[$key]:"blank");
}

echo "<pre>";
print_r($res);