我正在尝试编写一些PHP代码,用于通过电子邮件发送数据库中每个用户(大约500个)的用户名。我已成功设法为每个用户提取电子邮件地址和用户名,并将它们存储在一个数组中。但是,我无法弄清楚如何使用各自的用户名向每个用户发送电子邮件。我很确定我需要使用foreach
循环来做到这一点,但我没有运气。
这就是我所拥有的。
<?php
include('databaseConn.php');
$query = mysql_query("SELECT * FROM staff");
$emailArray;
while ($row = mysql_fetch_array($query)) {
$emailArray[] = array($row['email']=>$row['username']);
}
print_r($emailArray); //This associative array now contains each username along with their respective email address.
?>
==的 * ** * ** * ** * * === 使用邮件功能
<?php
include('functions/core.php');
$query = mysql_query("SELECT * FROM users");
$emailArray;
while ($row = mysql_fetch_array($query)) {
$emailArray[] = array($row['email']=>$row['username']);
}
foreach($emailArray as $email => $username) {
echo $username; // outputs the indexes.
$subject = 'Accoutn Details';
$message = 'This email contains your login details.<br/><br/>
<b>Username: '.$username.'</b><br/>
<br/><br/>Kind regards,<br/>';
$headers = 'From: noreply@xxxxx.co.uk' . "\r\n" .
'Reply-To: noreply@xxxxx.co.uk' . "\r\n" .
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($emailAddress, $subject, $message, $headers);
}
//print_r($emailArray);
?>
答案 0 :(得分:0)
如果您的问题是如何使用foreach ... http://www.php.net/manual/en/control-structures.foreach.php
例如:
foreach ($emailArray as $email => $username) {
// Send an email to $email with their $username
}
@Dagon是对的,如果没有别的东西你需要关联数组,就没有必要迭代两次。即使你确实需要一个数组,它也不一定是关联的;它可能是来自DB的原始行,您可以迭代它。您需要关联数组的唯一时间是您需要通过键(电子邮件地址)查找值(用户名),据我所知,您不需要做。
答案 1 :(得分:0)
错误的想法是在循环中使用邮件,除非它是一个关闭,听起来像它,大多数共享主机也不允许一次发送500封电子邮件。
$subject = 'Account Details';
$headers = 'From: noreply@xxxxx.co.uk' . "\r\n" .
'Reply-To: noreply@xxxxx.co.uk' . "\r\n" .
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
while ($row = mysql_fetch_array($query)) {
$message = 'This email contains your login details.<br/><br/>
<b>Username: '.$row['username'].'</b><br/>
<br/><br/>Kind regards,<br/>';
mail("$row['email']", $subject, $message, $headers);
}