問題描述
以下代碼在每次 while()
循環(huán)時都會產(chǎn)生非法偏移錯誤:
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
設(shè)置為 $email['username']
如果 $email['username']
不為空,如果為為空,$name
應(yīng)該設(shè)置為$email
.$email
由 while()
語句設(shè)置,來自 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 循環(huán)設(shè)置的 $email 變量
You are overwriting the $email variable set by the while loop
while($email = mysql_fetch_assoc($query)) {
然后你就覆蓋了它:
$email = $email['email'];
so $email
將成為字符串而不是數(shù)組.你可以把它改成
so $email
will become a string and not an array. You could change this to
$email_address = $email['email']
這篇關(guān)于“非法抵銷"循環(huán)內(nèi)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!