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

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计