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'
4

3 回答 3

6

compact()extract()(将关联数组提取到本地符号表中)相反,并且是您要使用的。

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

键盘

于 2013-03-12T12:45:30.583 回答
5

该函数compact正是这样做的:

$array = compact('green', 'red', 'blue', 'pink', 'orange');
于 2013-03-12T12:45:21.733 回答
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'];
于 2013-03-12T12:46:39.343 回答