2012-01-04 21 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