如何为 Mandrill 创建动态数组 API

How to create a dynamic array for Mandrill API

我想使用一个 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
        );
    }

所以我想以动态方式创建该数组,这可能吗?

您应该根据需要转换数组。

使用此代码

function sendEmailToArray($subscribers_email){
    //$subscribers_email = array(
    //    'email_1@xxx.com',
    //    'email_2@xxx.com',
    //    'email_3@xxx.com'
    //);

    $final_subscribers_email = array();
    foreach ($subscribers_email as $key => $value) {
        array_push($final_subscribers_email, array("email" => $value));
    }

    $mandrill_message = array(
        // ...blah blah, doesn't matter
        // To send to only one email address:
        'to' => $final_subscribers_email,
        // ...blah blah, doesn't matter
    );
}

您可以使用 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),
   );
}