Php循环foreach行为奇怪,打印出错误的html


Php loop foreach behave strange and prints out wrong html

我正试图准备电子邮件html,我有2组客户-1组只会收到电子邮件2组将收到相同的电子邮件+代金券。我准备了一个简短的代码来说明这个问题。

$voucher='<div>VOUCHER IMAGE COMES HERE</div>';//only group for voucher must see it
$mail_description='Here comes my mail text';
$voucherarray=array("mail1@gmail.com","mail3@gmail.com");
$mailaray=array("mail1@gmail.com","mail2@gmail.com");
$html='';
foreach($mailaray as $email){
$html.='<div>'.$mail_description.'</div>';
if(in_array($email, $voucherarray)){
$html.=$voucher;
echo $email.'is for voucher';
}else{ $email.'is not for voucher';}
$html.='<table><tr><td>here is some other text</td></tr></table>
<div clss="footer"></div>';
mail($email,'subject',$html);
}
echo $html.'<br />';    

这段代码打印出:

mail1@gmail.comis for voucher
Here comes my mail text
VOUCHER IMAGE COMES HERE
Here comes my mail text
here is some other text
Here comes my mail text
VOUCHER IMAGE COMES HERE
Here comes my mail text
here is some other text

有什么问题,为什么它打印出代金券图像来这里两个邮件只有一个是代金券?它还向所有组用户发送相同的邮件

您需要将在邮件中发送的html与发送邮件的作业希望看到的输出分开。第二件事是,您需要在每次迭代后清空邮件主体变量,您不希望每个客户机都接收以前客户机的邮件内容。

$voucher='<div>VOUCHER IMAGE COMES HERE</div>';//only group for voucher must see it
$mail_description='Here comes my mail text';
$voucherarray=array("mail1@gmail.com","mail3@gmail.com");
$mailaray=array("mail1@gmail.com","mail2@gmail.com");
$html='';

foreach($mailaray as $email){
      $mailHtml = '';
      $mailHtml.='<div>'.$mail_description.'</div>';
      if(in_array($email, $voucherarray)){
            $mailHtml.=$voucher;
            echo $email.'is for voucher<br>';
      }else{ 
            echo $email.'is not for voucher<br>';
      }
      $mailHtml.='<table><tr><td>here is some other text</td></tr></table><div clss="footer"></div>';
      mail($email,'subject',$mailHtml);
      $html .= '<br>' . $mailHtml;
}
echo $html.'<br />';