2012-07-08 199 views
0

我是新來的變量變量的概念,不認爲我完全理解。變量PHP變量

我所試圖做的就是創建一個for循環,將填充基於變量數量可變的數組。

我試圖取代:(手動硬編碼)

$numCorrectArray = array(1=>$q01TotalCorrect, 2=>$q02TotalCorrect, 3=>$q03TotalCorrect, 4=>$q04TotalCorrect, 5=>$q05TotalCorrect, 6=>$q06TotalCorrect, 7=>$q07TotalCorrect, 8=>$q08TotalCorrect, 9=>$q09TotalCorrect, 10=>$q10TotalCorrect, 11=>$q11TotalCorrect, 12=>$q12TotalCorrect, 13=>$q13TotalCorrect, 14=>$q14TotalCorrect, 15=>$q15TotalCorrect, 16=>$q16TotalCorrect, 17=>$q17TotalCorrect, 18=>$q18TotalCorrect, 19=>$q19TotalCorrect, 20=>$q20TotalCorrect, 21=>$q21TotalCorrect, 22=>$q22TotalCorrect, 23=>$q23TotalCorrect, 24=>$q24TotalCorrect, 25=>$q25TotalCorrect, 26=>$q26TotalCorrect, 27=>$q27TotalCorrect, 28=>$q28TotalCorrect, 29=>$q29TotalCorrect); 

有了:(動態)

$numCorrectArray = array(); 

for($i=1; $i <= $stats->numberOfQuestions; $i++) { 

    if($i < 10) { 
     $questionNumber = "0" . $i; 
    } else { 
     $questionNumber = $i;    
    } 
    $varName = "q" . $questionNumber . "TotalCorrect"; 

array_push($numCorrectArray, $$varName); 
} 

我將如何做到這一點?由於

+0

爲什麼你有如此好奇的命名變量? – KingCrunch 2012-07-08 20:48:23

+0

$我似乎是用來初始化 – Musa 2012-07-08 20:50:57

+1

「*我是新來的變量變量的概念** ***」? – Lion 2012-07-08 20:51:26

回答

0

下面的方法,我認爲是比較容易理解,因爲類似於普通的PHP代碼。 Here you can learn more

$numCorrectArray = array(); 

$prefix = 'q'; 
$sufix = 'TotalCorrect'; 

for($i=1; $i <= 30; $i++) { 

    if($i < 10) { 
     $questionNumber = "0" . $i; 
    } else { 
     $questionNumber = $i;    
    } 

    ${$prefix . $questionNumber . $sufix} = $i; 

    $numCorrectArray[$i] = ${$prefix . $questionNumber . $sufix}; 

}