使用for循环从MySQL查询中逐步选择值

时间:2012-10-01 06:32:41

标签: php mysql for-loop

我正在尝试使用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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

替换此行:

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

用这个:

echo $$dayVar . ': ' . $dayVarCount . '<br>';

答案 2 :(得分: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>";
    }       
}
?>

你也可以尝试这个代码。

答案 3 :(得分: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>';
    }      
}