0

我想知道是否可以在可变变量数组引用中获取 x 值位置(即第二个)。

下面的代码适用于第一个数组,但不适用于第二个。

// WORKS FINE //
$my1stArray= array( 'red', 'green', 'blue');
$var_1st = 'my1stArray';

// for each lopp of var var works fine
echo " - my1stArray Values - <br>";
foreach ($$var_1st as $k => $v){
echo $k." : ".$v." <br>";
}
// direct access also works
echo "my1stArray 3rd value: ".${$var_1st}[2]."<br>";

// Not so good! //
$my2ndArray = array(
    'color' => '#ff0000',
    'face' => 'helvetica',
    'size' => '+5',
);
$var_2nd = 'my2ndArray';

// for each lopp of var_2nd works fine
echo "<br> - my2ndArray Values - <br>";
foreach ($$var_2nd as $k => $v){
echo $k." : ".$v." <br>";
}
/** try to access 2nd value in array with position **/
echo "my2ndArray 2rd value: ".${$var_2nd[1]}[0]."<br>";
echo "my2ndArray 2rd value: ".${$var_2nd}[1][0]."<br>";
4

2 回答 2

1

Your last example in your code is not working for the same reason that the following code does not work:

$a = array('akey'=>'a','bkey'=>'b');
echo $a[0];

The reason is the key is set to a string and must be accessed as such. To fix my example I would need to change it to:

$a = array('akey'=>'a','bkey'=>'b');
echo $a['akey'];

To fix your example you need to change your last echo so that it references the key as a string:

echo "my2ndArray 2rd value: ".${$var_2nd}['color']."<br>";
于 2012-09-05T02:30:20.870 回答
1

好吧,在评论中我说“不,你不能”,但实际上有一种方法。这是一个示例(没有变量):

$my2ndArray = array(
    'color' => '#ff0000',
    'face' => 'helvetica',
    'size' => '+5',
);
$keys = array_keys($my2ndArray);
echo "my2ndArray 2nd value: " . $my2ndArray[$keys[1]]  . "<br>";

看起来不是很好,但应该可以。并不是说如果你对数组进行排序,键索引就会改变。

另一种方法是使用我在评论中提到的计数器和循环。但这会更难看……

于 2012-09-05T02:57:55.160 回答