简单数组foreach

时间:2015-06-25 12:07:50

标签: php

我确信这很简单......但我似乎无法弄明白。我需要向每个提到积分的电子邮件地址发送电子邮件。但这两封电子邮件都有36分。

$emails = $userTools->weeklyMail();

的print_r:

Array
(
    [0] => Array
        (
            [0] => email1@gmail.com
            [1] => 
            [2] => 36
        )

    [1] => Array
        (
            [0] => email2@gmail.com
            [1] => 
            [2] => 25
        )

)

循环:

foreach($emails as $email)
{
        $email = $email[0];
        $subject = "You have ".$email[2]." points!!! !!!";
        // The message
        $message = "Hello\r\nYou have ".$email[2]." points .";
        $helperClass->sendEmail($email, $subject, $message);
}

4 个答案:

答案 0 :(得分:5)

您的问题是您覆盖引用变量$email,这意味着$email[2]未定义。

更改为:

foreach($emails as $email)
{
        // $email = $email[0]; You can't use $email[2] if $email is overwritten
        $subject = "You have ".$email[2]." points!!! !!!";
        // The message
        $message = "Hello\r\nYou have ".$email[2]." points .";
        $helperClass->sendEmail($email[0], $subject, $message);
}

答案 1 :(得分:1)

删除

$email = $email[0];

然后改变最后一行:

$helperClass->sendEmail($email[0], $subject, $message);

答案 2 :(得分:1)

试试这个

 $count_emails=count($emails);
 for($i=0;$i<$count_emails;$i++)
 {
    $email_addr = $email[$i][0];
    $subject = "You have ".$email[$i][2]." points!!! !!!";
    // The message
    $message = "Hello\r\nYou have ".$email[2]." points .";
    $helperClass->sendEmail($email_addr, $subject, $message);
 }

答案 3 :(得分:0)

所以在$ email = $ email [0]之后;你重新分配foreach变量$ email。在变量$ email中,我们只有电子邮件地址。在使用$ email [2]的其他代码中,PHP返回带有邮件的字符串的第3个符号。

试试这段代码

foreach($emails as $email)
{
        $email_address = $email[0];
        $points = $email[2];

        $subject = "You have ".$points." points!!! !!!";
        // The message
        $message = "Hello\r\nYou have ".$points." points .";
        $helperClass->sendEmail($email_address, $subject, $message);
}