是否有比较 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"
);
array_diff可能会让您走上正确的道路。虽然它没有给出您正在寻找的确切输出,但它会向您显示两个数组之间的差异。
正如马克指出的那样,array_diff_assoc可能会更有帮助,因为它维护数组索引。
如前所述,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;
}
没有什么默认的,我手上有一些时间:) 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);
?>
检查这个,更有效的解决方案:
$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);