简体   繁体   中英

PHP use Array of indexes as Array index

I have an array of indexes and a value to insert.

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

How can i use the indexes array like this to insert a value:

$array_to_fill[$indexes] = 820;

To produce a nested array of this style:

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

i tried using pointers to maybe save the location of the array but that only saves a chunk of the array not the position. I have spent too many hours on this and help would be very much appreciated.

You can create a "pointer" with & and update it to point to the latest level you create :

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM