PHP 使用索引数组作为数组索引

PHP use Array of indexes as Array index

我有一个索引数组和一个要插入的值。

$indexes = [0,1,4];
$value_to_insert = 820;
$array_to_fill = [];

我如何使用这样的索引数组来插入一个值:

$array_to_fill[$indexes] = 820;

要生成这种样式的嵌套数组:

$array_tree = [
            "0" => [
                "1" => [
                    "4" => 820
                ]
            ]
        ]

我试过使用指针来保存数组的位置,但这只保存了数组的一部分而不是位置。我在这上面花了太多时间,非常感谢您的帮助。

您可以使用 & 创建一个“指针”并更新它以指向您创建的最新级别:

$indexes = [0,1,4];
$value_to_insert = 820;
$array_to_fill = [];

$current_root = &$array_to_fill ; // pointer to the root of the array
foreach($indexes as $i)
{
    $current_root[$i] = array(); // create a new sub-array
    $current_root = &$current_root[$i] ; // move the pointer to this new level
}
$current_root = $value_to_insert ; // finally insert the value into the last level
unset($current_root);

print_r($array_to_fill);