循环遍历object方法中使用的一串值

时间:2016-05-24 22:21:33

标签: php object for-loop

我的字符串包含以逗号分隔的电子邮件地址。

我需要使用addBcc方法将它们添加到我的邮件程序对象($ mailin)中。该对象支持方法链接。

我尝试在for循环中echo来实现我想要的但是按照预期,它不起作用。它给了我500个错误。

期望的结果;

$mailin = new Mailin('my@mail.com', 'apikey');
$mails = "a@example.com, b@example.com";
$mailin->
    addBcc('a@example.com')->
    addBcc('b@example.com')->

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用explodeforeach循环,如下所示:

$mails = "a@example.com, b@example.com";
$bcc = explode(',',$mails);

foreach($bcc as $address){
    $mailin->addBcc(trim($address));
}

答案 1 :(得分:0)

如果你有:

$mails = "a@example.com, b@example.com"; 

您可以以下内容获取包含所有单独电子邮件的数组:

$mailArray = [];
$result = [];      //this will be the result
list($mailArray) = explode(",", $mails);//here you are separating the emails
foreach ($mailArray as $value)
{
    $result[] = trim($value);//here you are taking out the whitespaces left behind
}

$result将是一个包含您要使用的电子邮件的数组。 如果你想查看数组,你可以这样做:

foreach ($result as $value)
{
  echo "-->{$value}<br>";
}

如果您想在之前的代码中使用它,它将类似于以下内容:

$mailin->
    addBcc($result[0])->
    addBcc($result[1])->
//... rest of your code