2014-11-08 74 views
0

我有两个来自不同来源(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 />'; 
 
     } 
 
    } 
 
?>

+0

哪旧地址应该被替换?您的示例没有任何地址在域更改。 – Barmar 2014-11-08 16:21:08

+1

如果在不同域中有两个具有相同名称的地址,会发生什么情况? '[email protected],john @ example2.org'? – Barmar 2014-11-08 16:22:33

+0

我的意思是像“[email protected]”,应该用“[email protected]”取代 – booog 2014-11-08 16:24:24

回答

0

制作一部键关闭名称$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 />'; 
    } 
} 
+0

太好了,非常感谢Barmar! – booog 2014-11-08 16:37:35

+0

这个工作,并会得到我无法找到自己的结果。所以对我来说重要的学习部分是创建一个新的数组,而不是寻找各种数组函数。再次感谢你,你帮了我很多,而且速度非常快! – booog 2014-11-08 16:40:58