"Illegal offset" 循环内部

"Illegal offset" inside of loop

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

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

我正在尝试将 $name 设置为 $email['username'] 如果 $email['username'] 不为空 ,并且如果 空的,$name应该设为$email$email 由来自 mysql_fetch_assoc()while() 语句设置。这是我目前的代码:

// 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']

您有一个名为 $email 的数组,它包含数据库行中的所有列。而您仅使用电子邮件列的值覆盖该对象:

while($email = mysql_fetch_assoc($query)) {
    // add to count
    $num++;

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

不要那样做。调用行对象 $row 会更有意义。您应该命名变量,以便清楚地知道它们是什么。

while($row = mysql_fetch_assoc($query)) {
    // add to count
    $num++;

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