php - "Illegal offset"循环内部

标签 php mysql email loops while-loop

<分区>

每次 while() 循环时,以下代码都会产生非法偏移错误:

Warning: Illegal string offset 'username' in /Applications/MAMP/htdocs/admin/scripts/email_owners_send.php on line 48

我正在尝试将 $name 设置为 $email['username'] if $email['username'] < strong>不为空,如果为空,$name 应设置为$email$emailwhile() 语句设置,来自 mysql_fetch_assoc()。这是我目前的代码:

// print out all the email address recipients
$query = mysql_query("SELECT * FROM ownersemails WHERE deleted=0 LIMIT 5");
$recipients = '';
$total = mysql_num_rows($query);
$num = 0;
while($email = mysql_fetch_assoc($query)) {
    // add to count
    $num++;

    // set email
    $email = $email['email'];

    // set name as username if apparant
    if(!empty($email['username'])) {
        $name = $email;
    }
    else {
        $name = $email['username'];
    }

    // add to recipients string (=. append)
    $recipients .= '{ "email": "'.$email.'", "name": "'.$name.'" }';
    // only add a comma if it isn't the last one
    if($num!=$total) {
        $recipients .=',';
    }
}

最佳答案

您正在覆盖由 while 循环设置的 $email 变量

 while($email = mysql_fetch_assoc($query)) {

然后在这里你覆盖它:

$email = $email['email'];

所以 $email 将变成一个字符串而不是一个数组。您可以将其更改为

$email_address = $email['email']

关于php - "Illegal offset"循环内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30038096/

相关文章:

php - undefined variable 实际上被定义了吗?

php - Facebook PHP SDK 3.0 - OAuthException : An active access token must be used to query information about the current user

php - mysql_real_escape_string 应该是我在注册表单中输入的密码吗?

ruby - 具有多个 OR 参数的 imap 搜索语法

c++ - C++ 中的电子邮件验证

javascript - 通过电子邮件发送生成的 Highchart 图像

php - Laravel 8 - 未登录时如何重定向到登录页面

PHP:使用外部连接文件时关闭mysql连接

mysql - 值(value)不断重复

mysql - 在 ALTER TABLE 或 DROP INDEX 命令完成之前终止它