【问题标题】:PHP make a multidimensional associative array from key namesPHP从键名创建一个多维关联数组
【发布时间】:2019-10-19 10:04:23
【问题描述】:

即使它已记录在案,我也需要帮助以更好地理解此代码(仅参考)。我已经检查了教程,但它们没有帮助我。

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

(来源:https://stackoverflow.com/a/31103901/4741362@Derokorian)

【问题讨论】:

    标签: php arrays multidimensional-array associative


    【解决方案1】:

    我会尝试解释它让你更好地理解它,请参阅工作代码here。我希望它能帮助你理解这个$curr = &amp;$curr[$key]; 行。 $currforeach 开始之前指向空的$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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多