2012-09-26 25 views
0

我正在使用while循環,我需要能夠將變量的值分配給新變量的名稱。這裏是環($ SLIDE_NUMBER總是返回數):如何在新變量名中使用變量?

$slide_number = theme_get_setting('slides_number'); 
$count = '1'; 

while ($count <= $slide_number) { 
    $slide_path = theme_get_setting('slide_path_'.$count.''); 
    if (file_uri_scheme($slide_path) == 'public') { 
     $slide_path = file_uri_target($slide_path); 
    } 
    $count++; 
} 

所以我們可以說$ SLIDE_NUMBER爲2。我需要產生$ slide_path_1和$ slide_path_2,讓我怎麼了$ count變量添加到$ slide_path創建$ slide_path_1和$ slide_path_2?

+0

爲什麼不使用數組呢? – pmakholm

+1

也許[variablevariables](http://php.net/manual/en/language.variables.variable.php)是你正在尋找的東西? – complex857

+0

此問題已被提問並回答數百次...請在再次提問之前嘗試搜索功能:) – rdlowrey

回答

2

雖然我不變量推薦的變量,這應該這樣做:

$slide_path = "slide_path_" . $slide_count; 
echo $$slide_path; 
0

我很困惑。如果您只需要循環的上一次運行信息,請在循環末尾有一個變量來保存該信息。或者將所有這些加載到一個聲明的數組中,然後在加載它之後執行所需的操作。

0

你正在做的事情是非常糟糕的做法...... 改爲使用數組來做到這一點。看看數組是如何工作的,你可以將所有的值附加在一個列表中,然後你可以根據需要查看它們。考慮以下幾點:

$slide_number = theme_get_setting('slides_number'); 
$count = '1'; 
$array_of_slides = array(); 

while ($count <= $slide_number) { 
    $slide_path = theme_get_setting('slide_path_'.$count.''); 
    if (file_uri_scheme($slide_path) == 'public') { 

    $slide_path = file_uri_target($slide_path); 

    // this line appends your value to the end of the array 
    $array_of_slides[] = file_uri_target($slide_path); 
    } 
    $count++; 
} 

// this will print out the array so that you can see it 
var_dump($array_of_slides); 

旁註:你正在嘗試做的理由是這樣的壞習慣,因爲如果你有宣佈爲你的程序4個十億變量會崩潰肯定,並可能需要您的操作系統下用它。

相關問題