PHP比较数组并替换值
问题描述:
我有两个来自不同来源(MySQL,Excel)的电子邮件列表,类似两个我的 示例。我在php中创建了两个数组,比较它们。 “$ mail_old”数组是包含几百个地址的主列表,在“$ mail_new” 中有更改。名称相同,但一些域名已更改。PHP比较数组并替换值
首先,我想检查哪个新地址不会出现在旧列表中,哪个 工作得很好。但我找不到替代它们的方法,array_replace()似乎没有帮助这里。 array_diff()也努力检查差异,但我没有得到任何进一步的。
这是我到目前为止,如果有人可以给我一个提示如何 旧地址取代新的。
非常感谢!
<?php
$mail_old = array('[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]',);
$mail_new = array('[email protected]', '[email protected]', '[email protected]', '[email protected]');
foreach ($mail_new as $changed) {
if (!in_array($changed, $mail_old)) {
echo 'Address ' . $changed . ' is new.<br />';
}
}
?>
答
制作一部键关闭名称$mail_old
关联数组:
$mail_by_name = array();
foreach ($mail_old as $i => $addr) {
list ($name, $domain) = explode('@', $addr);
$mail_by_name[$name] = $i;
}
然后把新的数组中测试每名反对这样的:
foreach ($mail_new as $changed) {
list($name, $domain) = explode('@', $changed);
if (isset($mail_by_name[$name])) {
if ($mail_old[$mail_by_name[$name]] != $changed) {
echo 'Address ' . $mail_old[$mail_by_name[$name]] . ' changed to ' . $changed . '.</br>';
$mail_old[$mail_by_name[$name]] = $changed;
}
} else {
echo 'Address ' . $changed . ' is new.<br />';
}
}
哪旧地址应该被替换?您的示例没有任何地址在域更改。 – Barmar 2014-11-08 16:21:08
如果在不同域中有两个具有相同名称的地址,会发生什么情况? '[email protected],john @ example2.org'? – Barmar 2014-11-08 16:22:33
我的意思是像“[email protected]”,应该用“[email protected]”取代 – booog 2014-11-08 16:24:24