PHP 从键名创建一个多维关联数组

PHP make a multidimensional associative array from key names

即使它被记录在案,我也需要帮助才能更好地理解这段代码(仅供参考)。我已经查看了教程,但它们对我没有帮助。

// initialize variables
$val = 'it works !';
$arr = [];

// Get the keys we want to assign
$keys = [ 'key_1', 'key_2', 'key_3', 'key_4' ];

// Get a reference to where we start
$curr = &$arr;

// Loops over keys
foreach($keys as $key) {
   // get the reference for this key
   $curr = &$curr[$key];
}

// Assign the value to our last reference
$curr = $val;

// visualize the output, so we know its right
var_dump($arr);
echo "<hr><pre>$arr : "; print_r($arr);

(来源: @Derokorian)

我会尝试解释一下,让您更好地理解它,请参阅工作代码here。我希望它能帮助您理解这一 $curr = &$curr[$key]; 行。 $curr指向foreach开始之前的空$arr,在foreach中它通过引用将$key的值保存到$arr中由 $curr 指向,然后将 $arr 中新保存的 $key 的引用重新分配给 $curr 指针。

// initialize variables
$val = 'it works !';
$arr = [];

// Get the keys we want to assign
$keys = [ 'key_1', 'key_2', 'key_3', 'key_4' ];

// Get a reference to where we start
echo "create a space where to save the first key \r\n";
$curr = &$arr;

// Loops over keys
$i = 1;
foreach($keys as $key) {

    echo "**************** Iteration no $i ******************\r\n";
    // echo "save the value \"$key\" to the reference created earlier in the $curr variable for the empty array above where the kesy are actually being saved \r\n";

    // get the reference for this key
    echo "Now save the value of $key to the array reference present in $curr and then assigne the reference of newly saved array item to $curr again \r\n";
    $curr = &$curr[$key];
    print_r($arr);

   $i++;
   echo "\r\n\r\n";
}

// Assign the value to our last reference
$curr = $val;

// visualize the output, so we know its right
print_r($arr);