0

我正在尝试使用 for 循环通过 MySQL 查询选择增量值。我在下面包含了示例代码:

<?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 = $dayVar."_count"; // Don't really need this anymore, so removed.
        $dayVarCount = $row[$$dayVar];
        echo "$$dayVar.': '.$dayVarCount<p>"; // Edited.
    }      
}
?>

我想我已经接近了,但是当我运行代码时,我的页面显示如下:

$day_1.': '.0

$day_2.': '.2

$day_3.': '.5

有什么额外的建议吗?感谢您的大力帮助!

4

4 回答 4

1

替换这一行:

echo "$$dayVar.': '.$dayVarCount<p>";

有了这个:

echo $$dayVar . ': ' . $dayVarCount . '<br>';
于 2012-10-01T07:05:07.310 回答
1

尝试一个变量变量:

for ($i = 1; $i <= 3; $i++) 
{
    $dayVar = "day_".$i;
    $dayVarCount = $dayVar."_count";
    $$dayVarCount = $row[$$dayVar];
    echo $$dayVar.': '.$$dayVarCount.'<p>'; // Edited.
}

这基本上使用字符串来通过名称引用变量。

只是这样想:

$variable = 'hello';

$string = 'variable';

echo $$string;
// Is the same thing as:
echo $variable;

// Because you can thing of $$string as ${$string} ---> $variable when {$string} is interpreted into 'variable'

http://php.net/manual/en/language.variables.variable.php

于 2012-10-01T06:40:04.187 回答
0
<?php

$day_1="January 1";
$day_2="January 2";
$day_3="January 3";

$query = mysql_query("SELECT * FROM dates WHERE id = '$id'");

while ($row = mysql_fetch_assoc($query))
{
for ($i = 1; $i <= 3; $i++) 
    {
        $var = $."day_".$i;
        $day_$i_count=$row['$var'];
        echo "$day_$i: $day_$i_count<p>";
    }       
}
?>

你也可以试试这个代码。

于 2012-10-01T06:52:30.080 回答
0

这一切似乎都过于复杂,但可能我没有充分理解这个问题。这行得通吗?

$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))
{
    foreach ($day as $day_str) 
    {
        echo $day_str . ':' . $row[$day_str] . '<p>';
    }      
}
于 2012-10-01T07:06:58.530 回答