doufan6886 2012-07-19 22:13
浏览 77
已采纳

在foreach循环中的PHP foreach循环

I'm trying to do a foreach loop inside a foreach loop.

I have a form where the user type in some text and hit send. On the server site I loop through an array with email addresses and send out the text message.

Now I also want the user to be able to use variables in the textarea, like $name. So my loop should first loop through the emails, and then str_replace the userinput $name variable, with the names in my array.

The loop works fine with the email part ($tlf), but not the replace $name part.

Could some spot what I am doing wrong?

$message = stripslashes(strip_tags($_POST['message2']));
$tlf=array("name1","name2");
$test=array("mname1", "mname2");
$subject = "Hello world";
$from = "me@gmail.com";
$headers = "From: $from";

foreach($tlf as $name){
    $to = $name. "@gmail.com";
    foreach($test as $navn){
        $message = str_replace('$navn', $navn, $message);}
    mail($to,$subject,$message,$headers);
}

Thanks a lot.

EDIT: The output is an email sent. Say the user type in "hello $name". I want it to first loop through the $tlf array, in this case creating 2 emails. This goes in as $to in the first loop. This works.

Now the next loop should recognize the user input "hello $name" and loop through the $test array replacing the user $name variable.

The output would be 2 emails send.

  1. Mail output: to: name1@gmail.com message: hello mname1

  2. Mail output: to: name1@gmail.com message: hello mname2

Let me know if I need to explain better, its hard for me to explain sorry.

  • 写回答

2条回答 默认 最新

  • dongwen3437 2012-07-19 22:24
    关注

    Is this what you want?

    $message = stripslashes(strip_tags($_POST['message2']));
    $tlf=array(
                array("email" => "name1", "name" => "mname1"),
                array("email" => "name2", "name" => "mname2")
              );
    $subject = "Hello world";
    $from = "me@gmail.com";
    $headers = "From: $from";
    
    foreach($tlf as $contact){
        $to = $contact["email"] "@gmail.com";
        $replacedMessage = str_replace('$navn', $contact["name"], $message);
        mail($to,$subject,$replacedMessage,$headers);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型