“非法抵销"循环内

2021-12-26 00:00:00 email loops while-loop php mysql

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

The following code produces an illegal offset error every time the while() loops:

警告:第 48 行/Applications/MAMP/htdocs/admin/scripts/email_owners_send.php 中的非法字符串偏移用户名"

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.$emailwhile() 语句设置,来自 mysql_fetch_assoc().这是我目前的代码:

I'm trying to set $name to be $email['username'] if $email['username'] isn't empty, and if is empty, $name should be set to $email. $email is set by the while() statement, from a mysql_fetch_assoc(). This is my code at the moment:

// 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 变量

You are overwriting the $email variable set by the while loop

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

然后你就覆盖了它:

$email = $email['email'];

so $email 将成为字符串而不是数组.你可以把它改成

so $email will become a string and not an array. You could change this to

$email_address = $email['email']

相关文章