【问题标题】:Simple array foreach简单的数组 foreach
【发布时间】:2015-09-12 00:53:09
【问题描述】:

我确定这很简单......但我似乎无法弄清楚。我需要向提及这些要点的每个电子邮件地址发送一封电子邮件。但是两封邮件都有 36 分。

$emails = $userTools->weeklyMail();

打印_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);
}

【问题讨论】:

    标签: php


    【解决方案1】:

    您的问题是您覆盖了引用变量$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);
    }
    

    【讨论】:

    • 我个人在发布问题后立即使用 for 循环并且它有效,但您的问题解决了问题中发布的问题。只是想知道......哪个更快? Foreach 的 for?谢谢!
    • @ciprian,就性能而言,请阅读:stackoverflow.com/questions/3430194/…,但毫无疑问,foreach 更安全。例如,当您删除数组的一个元素以致缺少索引时会发生什么?它会在 for 循环中破坏您的代码。使用foreach,这不是问题。
    • 是的......这是真的。我刚刚将 id 添加到 $emails 查询中,并且不得不更改 for 循环。
    【解决方案2】:

    删除该行

    $email = $email[0];
    

    然后改变最后一行:

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

    【讨论】:

      【解决方案3】:

      试试这个

       $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);
       }
      

      【讨论】:

        【解决方案4】:

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

        试试这个代码

        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);
        }
        

        【讨论】:

          猜你喜欢
          • 2011-05-08
          • 2011-04-26
          • 1970-01-01
          • 2016-08-19
          • 2012-01-27
          • 2016-11-25
          • 1970-01-01
          • 2023-03-05
          • 1970-01-01
          相关资源
          最近更新 更多