首页 > 解决方案 > 将字符串变量插入数组

问题描述

我在我的 PHP 项目中使用了 Sendinblue SMTP,并且我想将事务性电子邮件发送到电子邮件的动态列表,问题是当我使用变量而不是字符串时出现语法错误。例如,这段代码效果很好:

    include 'Mailin.php';
    $mailin = new Mailin('senders@sender.com', 'key');
    $mailin->
    addTo(
        array(
                 'email1@email.com' => '', 'email2@email.com' => '', 'email3@email.com' => ''
            )
    )->

    setFrom('sender@sender.com', 'Test')->
    setReplyTo('sender@sender.com', 'Test')->
    setSubject('Example')->
    setText('Test')->
    setHtml($htmlContent);
    $res = $mailin->send();
    print_r($res);

但是,如果我使用变量而不是“addTo Array”中的字符串,则会显示语法错误,例如:

    $customers = '';
    foreach ($clientes as $customer) {

        for ($i=1; $i < 41; $i++) { 

            if ($customer['email'.$i]  != "" or $customer['email'.$i] != NULL) {

                $customers .= "'".$customer['email'.$i]. "' => '', " ; //for each customer's email add the email in " 'email@email.com' => '', " format
            }
        }
    }

    $customers = substr($customers, 0, -2); //removes last space and comma of the String

    include 'Mailin.php';
    $mailin = new Mailin('senders@sender.com', 'key');
    $mailin->
    addTo(
        array(
                 $customers
            )
    )->

    setFrom('sender@sender.com', 'Test')->
    setReplyTo('sender@sender.com', 'Test')->
    setSubject('Example')->
    setText('Test')->
    setHtml($htmlContent);
    $res = $mailin->send();
    print_r($res);

如果我使用 Print_r($customers) 函数,它会显示我在第一个示例中使用的确切字符串,即使我使用代码:

    $text = "'email1@email.com' => '', 'email2@email.com' => '', 'email3@email.com' => ''";

    if ($customers == $text) {
        print_r("Yes");
    }else{
        print_r("No");
    }

结果是“是”,但是当我在

    addTo(
        array(
                 $customers
            )
    )->

显示错误,但如果我直接使用字符串,则会发送电子邮件

    addTo(
        array(
                 'email1@email.com' => '', 'email2@email.com' => '', 'email3@email.com' => ''
            )
    )->

如果 $customers 变量具有所需的字符串,我不知道为什么它会显示错误。

您知道如何将变量与我需要发送的电子邮件一起使用吗?

标签: phpemailsendinblue

解决方案


您不会通过在其中连接字符串来构建数组=>。要在关联数组中创建元素,只需分配给该数组索引。

$customers = [];
foreach ($customers as $customer) {
    for ($i = 1; $i < 41; $i++) {
        if (!empty($customer["email" . $i])) {
            $customers[$customer["email" . $i]] = "";
        }
    }
}
include 'Mailin.php';
$mailin = new Mailin('senders@sender.com', 'key');
$mailin->
addTo($customers)->
...

另外,请参阅为什么一个变量对多个值的非等式检查总是返回 true?为什么你应该使用&&而不是||在你跳过空电子邮件时(我已经通过使用简化了!empty())。


推荐阅读