Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 简单数组foreach_Php - Fatal编程技术网

Php 简单数组foreach

Php 简单数组foreach,php,Php,我相信这很简单。。。但我似乎不明白。我需要向每个提到这些要点的电子邮件地址发送一封电子邮件。但两封邮件都有36分 $emails = $userTools->weeklyMail(); 打印: Array ( [0] => Array ( [0] => email1@gmail.com [1] => [2] => 36 ) [1] =>

我相信这很简单。。。但我似乎不明白。我需要向每个提到这些要点的电子邮件地址发送一封电子邮件。但两封邮件都有36分

$emails = $userTools->weeklyMail();
打印:

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

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

)
循环:

删除该行

$email = $email[0];
然后更改最后一行:

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

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

 $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);
 }
$count_emails=count($emails);
对于($i=0;$isendEmail($email\u addr,$subject,$message);
}

因此,在$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);
}

我个人在发布问题后立即使用了for循环,它起了作用,但您的问题解决了问题中发布的问题。只是想知道…哪个更快?Foreach of for?谢谢!@ciprian,就性能而言,请阅读以下内容:,然而,毫无疑问,
Foreach
更安全。例如n删除数组中的一个元素以便缺少索引?这会在for循环中中断代码。使用foreach,这不是问题。是的……没错。我刚刚将id添加到
$emails
查询中,并且必须更改for循环。
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);
}