构建数组密钥链


Building array key chain

是否可以采用一个值数组,例如:

$index = array('0' => '1', '1' => '4', '2' => '7');

并使用它来更新位置$update['1']['4']['7']处的另一个阵列的位置?

我想也许我可以做下面这样的事情(但似乎我做不到)。。。

for($build_key=0;$build_key<3; $build_key++){
    $this_key .= "[".$index[$build_key]."]";
}
$update.$this_key = 'new data in';

更新

我不确定数组将有多少级别,这就是为什么我尝试使用for循环(我在for循环中放了上面的"3",尽管我可能应该使用count($index)。

这样?

$x = $index[0];
$y = $index[1];
$z = $index[2];
$update[$x][$y][$z] = 'new data in';

这将适用于任何长度的阵列:

$index = array('0' => '1', '1' => '4', '2' => '7');
$where = &$update;
foreach ($index as $key => $value)
    $where = &$where[$value];      
$where = 'new data in';

不需要附加字符串,只需保留对当前数组的引用即可:

$target =& $update;
for($build_key=0; $build_key < 3; $build_key++){
 $target =& $target[$index[$build_key]];
}
$target = 'new data';

当然,如果$index总是有3个元素长,那么硬编码它会更容易!