如何将for循环变为变量?

时间:2014-03-21 22:21:26

标签: php email for-loop concatenation

所以,我有一个网站,我想向用户显示测试结果,但我也想将这些相同的结果通过电子邮件发送给评分者。我必须向用户显示结果的代码如下:

for($i=1; $i<=$totalquest; $i++){
    if($_POST[$i]!=$correct[$i]){
        echo "You answered Question $i incorrectly:<br> $question[$i] <br> You answered: $_POST[$i] <br> The correct answer is: $correct[$i]<p>";
        $score=$score-1;
    }
}

此代码非常有效。

当我尝试在其中创建包含该信息的电子邮件时,问题就出现了。

到目前为止,我有这个:

$message = $_SESSION["firstname"]." ".$_SESSION["lastname"]."'s score is ".$score."/".$totalquest." which equals ".$percent." percent.\r\n\r\n".
"The questions ".$_SESSION["firstname"]." got wrong are as follows:\r\n\r\n";
mail($to, $subject, $message, $headers);

哪个有效,但我无法理解如何将循环转换为$message变量。基本上我需要连接for循环的结果,创建一个字符串并将其放入$message变量。但我迷路了!

2 个答案:

答案 0 :(得分:0)

只需对.=使用$message,每次都将新邮件添加到旧邮件中(这也会在每个问题之间添加换行符):

$message = $_SESSION["firstname"]." ".$_SESSION["lastname"]."'s score is ".$score."/".$totalquest." which equals ".$percent." percent.\r\n\r\n".
"The questions ".$_SESSION["firstname"]." got wrong are as follows:\r\n\r\n";
for($i=1; $i<=$totalquest; $i++){
    if($_POST[$i]!=$correct[$i]){
        $message .= "You answered Question $i incorrectly:<br> $question[$i] <br> You answered: $_POST[$i] <br> The correct answer is: $correct[$i]<p>\r\n";
        echo "You answered Question $i incorrectly:<br> $question[$i] <br> You answered: $_POST[$i] <br> The correct answer is: $correct[$i]<p>";
        $score=$score-1;
    }
}
mail($to, $subject, $message, $headers);

答案 1 :(得分:0)

$emsg = "";  // email message
for($i=1; $i<=$totalquest; $i++){
    if($_POST[$i]!=$correct[$i])
    {
        $msg = "You answered Question $i incorrectly:<br> $question[$i] <br> You answered: $_POST[$i] <br> The correct answer is: $correct[$i]<p>";
        echo $msg;
        $emsg .= "<br/>\n" . $msg;
        $score=$score-1;
    }
}

$message = (the same stuff you have) . $emsg;