PHP:是否可以动态更改变量的名称?

时间:2011-12-07 10:55:14

标签: php variables dynamic-variables

我有代码从我的数据库中选择数据,然后将这些选定的值设置为变量。

但是我需要多次运行查询。我想知道我是否可以使用while / for循环运行查询x次并使用switch函数相应地更改变量名称?我不确定这是否值得做,更不用说可能,任何想法?感谢。

下面是我想要实现的代码,它可以正常工作。

////////////////////////////////////////////////////////////////////////////////////////////////////
$output1 = mysql_query("

SELECT `pOutputValue`,`cOutputValue` 
FROM `output` WHERE `teamID` = '$teamID' && `period` = '$currentStage' && `outputType`      = 'balance'

")or die($output1."<br/><br/>".mysql_error());

//assign the text located at the logo field (the path of the logo) to a variable     $slogan
while($row = mysql_fetch_assoc($output1)) 
{
$pBalance = $row['pOutputValue'];
$cBalance = $row['cOutputValue'];

}



////////////////////////////////////////////////////////////////////////////////////////////////
$output2 = mysql_query("

SELECT `pOutputValue`,`cOutputValue` 
FROM `output` WHERE `teamID` = '$teamID' && `period` = '$currentStage' && `outputType`     = 'marketShare'

")or die($output2."<br/><br/>".mysql_error());

//assign the text located at the logo field (the path of the logo) to a variable $slogan
while($row = mysql_fetch_assoc($output2)) 
{
$pMarketShare = $row['pOutputValue'];
$cMarketShare = $row['cOutputValue'];

}
//////////////////////////////////////////////////////////////////////////////////////////////////
$output3 = mysql_query("

SELECT `pOutputValue`,`cOutputValue` 
FROM `output` WHERE `teamID` = '$teamID' && `period` = '$currentStage' && `outputType` = 'salePrice'

")or die($output3."<br/><br/>".mysql_error());

//assign the text located at the logo field (the path of the logo) to a variable $slogan
while($row = mysql_fetch_assoc($output3)) 
{
$pSalePrice = $row['pOutputValue'];
$cSalePrice = $row['cOutputValue'];

}

?>

但是,我试图通过一个变量名更新的循环来运行查询。

<?php

$i = "0";

while($i<4)

{

switch ($i)

case "0";
$type = "balance";
break;

case "1";
$type = "marketShare";
break;

case "2";
$type = "salePrice";
break;

case "3";
$type = "unitPrice";
break;



$output = mysql_query("

SELECT `pOutputValue`,`cOutputValue` 
FROM `output` WHERE `teamID` = '$teamID' && `period` = '$currentStage' && `outputType` = '$type'

")or die($output."<br/><br/>".mysql_error());

//assign the text located at the logo field (the path of the logo) to a variable $slogan
while($row = mysql_fetch_assoc($output)) 
{
$c$type = $row['pOutputValue'];
$p$type = $row['cOutputValue'];


}

问题是如何更新变量名称

  $pBalance = $row['pOutputValue'];
  $cBalance = $row['cOutputValue'];

这甚至可能吗?或者它甚至值得做什么?

2 个答案:

答案 0 :(得分:3)

为什么不使用数组来保存值?然后问题变得微不足道。

答案 1 :(得分:1)

你可以这样做

$name = 'c' . $type;
$$name = $row['cOutputValue'];
$name = 'p' . $type;
$$name = $row['pOutputValue'];

但总的来说它不会很方便,阵列可能更适合这种情况。