1

嗨,我想使用 php 邮件功能发送循环数据,这是我的代码:

foreach ($data['query'] as $row){
    echo $row->name;
    echo "<br>";
    echo $row->time;
    echo "<br>";
    echo $row->dosage;
    echo "<br>";
    echo $row->frequency;
    echo "<br>";
    echo $row->quantity;
    echo "<br>";
}

$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com";
mail($to,$subject,$txt,$headers);

谁能告诉我如何将 foreach 循环数据附加到电子邮件正文中,我的意思是我想发送循环数据,而不是在正文中发送此文本(Hello World!)。

4

4 回答 4

1

连接$txt

$txt = "";
foreach ($data['query'] as $row){
    $txt .= $row->name;
    $txt .= "<br>";
    $txt .= $row->time;
    $txt .= "<br>";
    $txt .= $row->dosage;
    $txt .= "<br>";
    $txt .= $row->frequency;
    $txt .= "<br>";
    $txt .= $row->quantity;
    $txt .= "<br>";
}

$to = "somebody@example.com";
$subject = "My subject";
$headers = "From: webmaster@example.com";
mail($to,$subject,$txt,$headers);
于 2012-09-08T08:32:26.250 回答
1

纯字符串连接如下:

   $str = ''; 
   foreach ($data['query'] as $row){
      $str .= $row->name;
      $str .= "<br>";
      $str .= $row->time;
      $str .= "<br>";
      $str .= $row->dosage;
      $str .= "<br>";
      $str .= $row->frequency;
      $str .= "<br>";
      $str .= $row->quantity;
      $str .= "<br>";
    }

    $to = "somebody@example.com";
    $subject = "My subject";
    $headers = "From: webmaster@example.com";
    mail($to,$subject,$str,$headers);

    $str = ''; // empty the $str again
于 2012-09-08T08:32:38.820 回答
0
<?php
$dataArray  =   array('name','time','dosage','frequency','quantity');
$txt        =   '';
foreach ($data['query'] as $row)
{
    foreach($dataArray as $key=>$data)
    {
       $txt .= ($row->$data.'</br>');
    }
}

$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com";
mail($to,$subject,$txt,$headers);

?>
于 2012-09-08T08:40:50.743 回答
0

我认为这就是你所追求的:

    $to = "somebody@example.com";
    $subject = "My subject";
    $txt = "Hello world!";
    $headers = "From: webmaster@example.com";

    foreach ( $data['query'] as $row ) {
      $txt = $row->name;
      $txt .= "<br>";
      $txt .= $row->time;
      $txt .= "<br>";
      $txt .= $row->dosage;
      $txt .= "<br>";
      $txt .= $row->frequency;
      $txt .= "<br>";
      $txt .= $row->quantity;
      $txt .= "<br>";

      mail( $to, $subject, $txt, $headers );
    }

这会为每个循环发送一封邮件。如果你想要的话,你的问题还不清楚。您也可以收集所有数据,并将其作为 1 封电子邮件发送:

$to = "somebody@example.com";
$subject = "My subject";
$txt = "";
$headers = "From: webmaster@example.com";

foreach ( $data['query'] as $row ) {
  $txt .= $row->name;
  $txt .= "<br>";
  $txt .= $row->time;
  $txt .= "<br>";
  $txt .= $row->dosage;
  $txt .= "<br>";
  $txt .= $row->frequency;
  $txt .= "<br>";
  $txt .= $row->quantity;
  $txt .= "-- end of row<br>";

}

mail( $to, $subject, $txt, $headers );
于 2012-09-08T08:33:54.263 回答