【问题标题】:PHP use Array of indexes as Array indexPHP使用索引数组作为数组索引
【发布时间】:2021-12-25 21:08:48
【问题描述】:

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

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

我怎样才能像这样使用索引数组来插入一个值:

$array_to_fill[$indexes] = 820;

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

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

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

【问题讨论】:

    标签: php arrays multidimensional-array tree


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-02
      • 2014-04-29
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多