I need to send emails to multiple recipients. The number of recipients will vary depending on the data in the db.
Mandrill allows me to only add multiple recipients using an array.
Below is what works for multiple recipients
//email array that needs to be added to the 'to' key
$emailArray = ["example@example.com","test@test.com","hello@test.com","world@test.com"];
$mandrill = new Mandrill('xxxxxxxxxxxxxxx');
$message = array(
'subject' => 'Thanks for signing up',
'from_email' => 'support@test.com',
'to' => array(
array(
'email' => 'hello@test.com',
'name' => 'Hello Test'
),
array(
'email' => 'goodbye@test.com',
'name' => 'Goodbye Test',
)
),
'global_merge_vars' => array(
array(
'name' => 'FIRSTNAME',
'content' => 'JOHN'
),
array(
'name' => 'LASTNAME',
'content' => 'DOE')
));
//print_r($message);
$template_name = 'hello-world';
print_r($mandrill->messages->sendTemplate($template_name, $template_content, $message));
Below is what i need to generate dynamically depending on the length of the emailArray
to' => array(
//the below array should be dynamically generated
array(
'email' => 'hello@test.com',
'name' => 'Hello Test'
),
array(
'email' => 'goodbye@test.com',
'name' => 'Goodbye Test',
)
)
Here is the array. Currently with fixed values.
//email array that needs to be added to the 'to' key
$emailArray = ["example@example.com","test@test.com","hello@test.com","world@test.com"];
My questions is How do generate the 'To' values based on the length of the email array?
is there a way i can implode the entire array script?
An effective way would be to use array_map I have added in some code that also takes an array of names as well (I couldn't see where you were getting the names from in your code).
$toAddresses = array('example@example.com','test@test.com','hello@test.com','world@test.com');
$names = array('Exmaple', 'Test', 'Hello', 'World');
$mandrillTo = array_map( function ($address, $name) {
return array(
'email' => $address,
'name' => $name
);
},
$toAddresses,
$names
);
This passes the 0th element from each array into the function and returns an array of two values, then passes the 1st, 2nd etc and returns each result in a new array ($mandrillTo)
来源:https://stackoverflow.com/questions/20618901/how-to-generate-an-array-of-multiple-recipients-using-mandrill