我试图在循环之外创建一个循环变量变量。一切正常,但我遇到了这段代码的问题:
$dayVar."_count" = $dayVarCount;
完整代码如下:
<?php
$day_1="sep_28";
$day_2="sep_29";
$day_3="sep_30";
$query = mysql_query("SELECT * FROM table WHERE id = '$id'");
while ($row = mysql_fetch_assoc($query))
{
for ($i = 1; $i <= 3; $i++)
{
$dayVar = "day_".$i;
$dayVarCount = $row[$$dayVar];
echo $$dayVar . ': ' . $dayVarCount . '<br>';
$dayVar."_count". = $dayVarCount;
}
}
echo "$day_3_count";
?>
答案 0 :(得分:2)
我相信您的$ dayVar。“_ count”的变量赋值不正确或非法。我会尝试$ {$ dayVar。“_ count”}代替。
答案 1 :(得分:0)
正如Skrol29正确地说的那样,这条线不起作用:
赋值(将值赋给veriable)的格式始终为
<variablename> <assignmentoperator> <value>
php中的意味着:
$day_1 = "123"
正如您已经使用过的那样。
变量名通常不是通用的。如果需要此类功能,请使用数组。 PHP arrays
答案 2 :(得分:0)
你几乎在正确的地方......但是。
for ($i = 1; $i <= 3; $i++)
{
$dayVar = "day_".$i;
$dayVarCount = $dayVar."_count";
$$dayVarCount = $row[$$dayVar];
}
echo "$day_3_count";
答案 3 :(得分:0)
试试这个,
<?php
// Connect to server and select database.
$host = "host here";
$username="username here";
$password="pass here";
$db_name="db here";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
if(mysql_select_db("$db_name")){echo "Success";}else{echo "cannot select DB";}
$day_1="sep_28";
$day_2="sep_29";
$day_3="sep_30";
$id=1;
$query = mysql_query("SELECT * FROM `tab1` WHERE id = '$id'");
while ($row = mysql_fetch_assoc($query))
{
for ($i = 1; $i <= 3; $i++)
{
$dayVar = "day_".$i;
$dayVarCount = $row[$$dayVar];
echo $$dayVar . ': ' . $dayVarCount . '<br>';
${$dayVar."_count"} = $dayVarCount;
}
}
echo "$day_3_count";
?>
<?php
// close connection
mysql_close();
?>