按域名过滤电子邮件

时间:2013-01-08 11:53:37

标签: php arrays

假设我有两个阵列 -

$EmailList1 = array("abc@domain1.com", "def@domain2.com", "ghi@domain3.com");
$EmailList2 = array("jkl@domain1.com", "mno@domain4.com", "pqr@domain5.com");

现在我希望我的新阵列 [mno@domain4.com,pqr@domain5.com]

jkl@domain1.com 之所以被省略,是因为它有(domain1.com)已经存在于$EmailList1

我的方法是首先获取$EmailList1的所有域,将其存储到数组中,循环遍历$EmailList2的每个项目,然后获取结果。

这是正确的方式还是可以有更好的方法?

3 个答案:

答案 0 :(得分:1)

你需要的只是

$EmailList1 = array("abc@domain1.com","def@domain2.com","ghi@domain3.com");
$EmailList2 = array("jkl@domain1.com","mno@domain4.com","pqr@domain5.com");

$diff = array_udiff($EmailList2, $EmailList1, function ($a, $b) {
    return strstr($a, '@') === strstr($b, '@') ? 0 : 1;
});

echo "<pre>";
var_dump($diff);

输出

array (size=2)
  1 => string 'mno@domain4.com' (length=15)
  2 => string 'pqr@domain5.com' (length=15)

答案 1 :(得分:0)

尝试:

$uniqueEmailsArray = array_unique(array_merge($EmailList1 , $EmailList2));

答案 2 :(得分:0)

试试这个 -

<?php
$EmailList1 = array("abc@domain1.com", "def@domain2.com", "ghi@domain3.com");
$EmailList2 = array("jkl@domain1.com", "mno@domain4.com", "pqr@domain5.com");

foreach($EmailList1 as $email){
  $emailArray = explode('@',$email);
  $domainArray[] = $emailArray[1];
}

$domains = array_unique($domainArray);

foreach($EmailList2 as $email){
  $emailArray = explode('@',$email);
  if(!in_array($emailArray[1], $domains) && !array_search($emailArray[1], $domains)){
    $sorted_emails[] = $email;
  }
}

print_r($sorted_emails);
?>