PHP:是否可以动态更改变量的名称?
我有从数据库中选择数据的代码,然后将这些选择的值设置为变量 但是,我需要多次运行查询。我想知道是否可以使用while/for循环运行x次查询,并使用switch函数相应地更改变量名?我不确定这是否值得做,更不用说可能了,有什么想法吗?谢谢 下面是我正在尝试实现的代码,它运行良好PHP:是否可以动态更改变量的名称?,php,variables,dynamic-variables,Php,Variables,Dynamic Variables,我有从数据库中选择数据的代码,然后将这些选择的值设置为变量 但是,我需要多次运行查询。我想知道是否可以使用while/for循环运行x次查询,并使用switch函数相应地更改变量名?我不确定这是否值得做,更不用说可能了,有什么想法吗?谢谢 下面是我正在尝试实现的代码,它运行良好 //////////////////////////////////////////////////////////////////////////////////////////////////// $output1
////////////////////////////////////////////////////////////////////////////////////////////////////
$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'];
}
?>
这可能吗?或者甚至值得这样做吗?为什么不使用数组来保存值呢?那么问题就变得无关紧要了。为什么不使用数组来保存值呢?然后问题就变得无关紧要了。你可以这样做
$name = 'c' . $type;
$$name = $row['cOutputValue'];
$name = 'p' . $type;
$$name = $row['pOutputValue'];
但总的来说,它不是很方便,数组可能更适合这种情况。您可以这样做
$name = 'c' . $type;
$$name = $row['cOutputValue'];
$name = 'p' . $type;
$$name = $row['pOutputValue'];
但总的来说,它不会很方便,数组可能更适合这种情况。好的,我会调查一下,我从来没有正确使用或学习过数组,因为我被它们弄糊涂了,也许我需要正确地学习它们。感谢使用数组我可以进行一次查询并将所有值存储在一个数组中,然后将每个值分配给一个变量?基本上,你可以使用$pMarketShare和$cMarketShare,而不是$marketShares['p']和$marketShares['c']啊,好吧,我会研究一下,我从来没有正确使用或学习过数组,因为我被它们弄糊涂了,也许我需要好好学习。感谢使用数组,我可以进行一次查询并将所有值存储在一个数组中,然后将每个值分配给一个变量?基本上,您可以使用$pMarketShare和$cMarketShare来代替$marketShares['p']和$marketShares['c']
$name = 'c' . $type;
$$name = $row['cOutputValue'];
$name = 'p' . $type;
$$name = $row['pOutputValue'];