2013-03-12 96 views
0

我想要設置變量負載,然後通過循環將它們添加到數組中,將鍵設置爲變量名稱,如下所示。將變量名稱設置爲鍵值將其值設置爲數組中的值

我只是不知道如何創建循環。

// create an array 
$array = array(); 

// Set up Variable 
$green = "31d944"; 
$red = "d92929"; 
$blue = "1b43d9"; 
$pink = "d96ad8"; 
$orange = "d98225"; 

// Loop though - not sure how this would work... 
for($i=0; $i<5; $i++){ 
    $array[] = $varNmae => $green; 
} 

// Output something like below 
$array['green']; // output '31d944' 
$array['red']; // output 'd92929' 
$array['blue']; // output '1b43d9' 
$array['pink']; // output 'd96ad8' 
$array['orange']; // output 'd98225' 
+0

直接訪問設置陣列,比如'$陣列[ '綠色'] = 「31d944」'? – 2013-03-12 12:45:05

回答

6

compact()extract()相反(提取關聯數組到本地符號表),並且要使用什麼。

$array = compact("green", "red", "blue", "pink", "orange"); 

CodePad

5

功能compact正是這樣做的:

$array = compact('green', 'red', 'blue', 'pink', 'orange'); 
0

在定義變量然後將它們添加到數組中而不是僅僅初始化數組時,是什麼想法?

// Can't you just use this? 
$ary = array(
    'green' => '31d944', 
    ... 
    'orange' => 'd98225', 
); 

可以用

foreach ($ary as $color => $val) { 
    echo "{$color} is equal to {$val}"; 
} 

被環或者作爲

echo $ary['green'];