我想使用一个Mandrill API调用向多个电子邮件地址发送电子邮件,以下是我们只发送一封电子邮件的行为:
<?php
$mandrill_message = array(
// ...blah blah, doesn't matter
// To send to only one email address:
'to' => array(
array(
'email' => $the_email,
)
),
// ...blah blah, doesn't matter
);
?>
这没关系,但是当我们想要将邮件发送到多个电子邮件地址时,我们必须这样:
<?php
$mandrill_message = array(
// ...blah blah, doesn't matter
// To send to more than one email:
'to' => array(
array(
'email' => $email_1,
),
array(
'email' => $email_2,
),
array(
'email' => $email_3,
),
),
// ...blah blah, doesn't matter
);
?>
正如您所看到的,我们重复了数组部分,现在假设我们有这个数组:
$subscribers_email = array(
'email_1@xxx.com',
'email_2@xxx.com',
'email_3@xxx.com'
);
我们怎么可能让mandrill代码使用$subscribers_email
?当然,我们可以在mandrill代码中编写电子邮件地址,如:
<?php
$mandrill_message = array(
// ...blah blah, doesn't matter
// To send to only one amil address:
'to' => array(
array(
'email' => 'email_1@xxx.com',
),
array(
'email' => 'email_2@xxx.com',
),
array(
'email' => 'email_3@xxx.com',
),
),
// ...blah blah, doesn't matter
);
?>
但那不是我想要的,想象我们需要让这个动态和功能,如:
function sendEmailToArray($subscribers_email){
$mandrill_message = array(
// ...blah blah, doesn't matter
// To send to only one amil address:
'to' => array(
$subscribers_email
),
// ...blah blah, doesn't matter
);
}
所以我想以动态的方式制作那个数组,这可能吗?
答案 0 :(得分:1)
您应该根据需要转换数组。
使用此代码
{{1}}
答案 1 :(得分:1)
您可以使用array_walk
。
$subscribers_email = array(
'email_1@xxx.com',
'email_2@xxx.com',
'email_3@xxx.com'
);
sendEmailToArray($subscribers_email);
function sendEmailToArray($subscribers_email){
// Convert the array
array_walk($subscribers_email, function(&$input){
$input = array('email' => $input);
});
// Send the emails
$mandrill_message = array(
'to' => array($subscribers_email),
);
}