忽略FOREACH函数/ PHP中的重复项

时间:2015-11-10 13:07:18

标签: php

我正在寻找一个php解决方案,以确保@mail不会处理任何重复的电子邮件地址。

$get_partner_emails = "SELECT email_address FROM partners WHERE partner_id ='$partner_id' AND active ='yes'";
																
if ($email_addresses = $connect->query($get_partner_emails)) {
  foreach ($email_addresses as $email_address) {
    $email_address = $email_address['email_address'];
    @mail($email_address, $partner_subject, $partner_message, $partner_headers);
  }
} else {
  echo "Error: No Partner Email Addresses Found<br>";
}

2 个答案:

答案 0 :(得分:1)

一种解决方案是过滤地址,如下:

<?php 

$get_partner_emails = "SELECT email_address FROM partners WHERE partner_id ='$partner_id' AND active ='yes'";

$adresses = array();

if ($email_addresses = $connect->query($get_partner_emails)) {
  foreach ($email_addresses as $email_address) {
    $adresses[$email_address['email_address']] = true;
  }
  foreach ($adresses as $adress => $true) {
    @mail($adress, $partner_subject, $partner_message, $partner_headers);
  }
} else {
  echo "Error: No Partner Email Addresses Found<br>";
}

如果您接受使用MySQL过滤地址,请在查询中添加DISTINCT,它会删除重复项,无需更改:

<?php 

$get_partner_emails = "SELECT DISTINCT email_address FROM partners WHERE partner_id ='$partner_id' AND active ='yes'";

if ($email_addresses = $connect->query($get_partner_emails)) {
  foreach ($email_addresses as $email_address) {
    $email_address = $email_address['email_address'];
    @mail($email_address, $partner_subject, $partner_message, $partner_headers);
  }
} else {
  echo "Error: No Partner Email Addresses Found<br>";
}

答案 1 :(得分:0)

您可以将发送的地址保存在“缓存”数组中,如下所示:

$handled = array();
foreach ($email_addresses as $address) {
    $email_address = $address['email_address'];
    if(isset($handled[$email_address ])) {
        // Already handled address
        continue;
    }
    @mail($email_address , $partner_subject, $partner_message, $partner_headers);
    $handled[$email_address ] = true;
}

......如果这就是你的意思。