【问题标题】:How to get a for loop into a variable?如何将for循环放入变量中?
【发布时间】:2014-03-21 22:21:26
【问题描述】:

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

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

这行得通,但我无法理解如何将 for 循环放入 $message 变量中。本质上,我需要连接 for 循环的结果,创建一个字符串并将其放入 $message 变量中。但我迷路了!

【问题讨论】:

  • 那么您希望将哪些结果放入 $message 变量中? $分?或者数组的一些成员
  • 您能否为消息的外观添加一些示例输出?

标签: php email for-loop concatenation


【解决方案1】:

只需将.= 用于$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);

【讨论】:

    【解决方案2】:
    $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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多