1

是否有比较 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

4 回答 4

5

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

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

于 2013-03-18T15:28:43.953 回答
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;
}

工作演示

于 2013-03-18T15:45:35.127 回答
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);
?>
于 2013-03-18T15:37:43.020 回答
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);
于 2013-03-19T09:01:19.357 回答