2012-01-04 127 views
1

嗨PHP变量变量是这甚至可能在PHPfor循环

<?php 
$sectorcount = $row_SectorCount['COUNT(*)']; 
//number of rows in database 
for ($i = 1; $i <= $sectorcount; $i++) 
{ 
${spendingname . $i}= array(); 
${spendingpercent . $i} = array(); 
${spendingid . $i} = array(); 

mysql_select_db($database_conn2, $conn2); 
$query_Spending = "SELECT CONCAT(spending.SectorID, spending.ExpenditureID) AS 'SpendingID', 
expenditure.ExpenditureName, spending.SpendingPercent, spending.SectorID 
FROM spending 
INNER JOIN expenditure ON spending.ExpenditureID = expenditure.ExpenditureID 
WHERE spending.SectorID = ".$i; 
$Spending = mysql_query($query_Spending, $conn2) or die(mysql_error()); 
$totalRows_Spending = mysql_num_rows($Spending); 
while($row_Spending = mysql_fetch_assoc($Spending)) 
{ 
${spendingname.$i}[] = $row_Spending['ExpenditureName']; 
${spendingpercent.$i}[] = $row_Spending['SpendingPercent']; 
${spendingid.$i}[]= $row_Spending['SpendingID']; 
} 
mysql_free_result($Spending); 
} 

我正打算在这方面这里用这个做。有一个数组可以使用where子句绘制值并单独显示它们

+2

为什么不使用数组? – 2012-01-04 02:00:33

回答

3

这是你在找什么:

for ($i = 0; $i < 14; $i++) { 
    ${'name' . $i} = $i; 
} 

echo $name3; 

但你应该刚使用阵列:

$name = array(); 
for ($i = 0; $i < 14; $i++) { 
    $name[$i] = $i; 
} 

echo $name[3]; 

如果您需要数组中的数组,请继续并执行此操作。如果你需要更多的嵌套数组,你可能应该使用某个类而不是所有的数组嵌套。

+0

谢谢!我想在一个像$ name这样的数组内的数组上尝试它。$ i = array();然后使用数据库将数据绘制出来 – 2012-01-04 02:05:45

+0

@JervisChionh您应该提供您认为有用的答案。您也应该通过点击复选标记来接受您的问题的答案。欢迎来到StackOverflow。 – 2012-01-04 02:08:00

+0

我有足够的代表!我很乐意这样做 – 2012-01-04 02:10:49

1

使用数组。这就是他们在那里。

+0

如果我想在数组中有一个数组,那该怎么办? – 2012-01-04 02:02:24

+0

然后就这样做。数组中的数组中的数组中的数组没有任何问题。数组中的数组 – 2012-01-04 02:04:05

+0

。它们被称为[嵌套数组](http://www.webcheatsheet.com/PHP/multidimensional_arrays.php)。 – Tomas 2012-01-04 02:06:41

2

首先,我建议使用数组来代替。 Variable variables并不意味着像这样使用。

这就是说,它可以通过访问${$name.$i},或者做类似

$varname = $name.$i; 
$$varname = 1; // or read from $$varname 
1

正如科林克说的,这是一个数组是什么!

但是,你问什么就可以实现:

Read More Here

基本上,

<?php 

for($i=0; $i<=13; $i++){ 

    $varname = "name" . $i; 
    $$varname=$i; 

} 

echo $name1; // 1 

?> 
1

它不会给所需的输出1,而不是将给予13

有何这样做的原因。你可以让array访问稍后使用

for($i=0; $i<=13; $i++) 
{ 
     $name[$i]=$i; 
} 

     echo $name[1];     *//it will echo 1