动态数组键

Ale*_*lex 8 php arrays multidimensional-array

我有一个像这样的字符串:

$string = 'one/two/three/four';

我把它变成一个数组:

$keys = explode('/', $string);

这个数组可以包含任意数量的元素,如1,2,5等.

如何为多维数组指定某个值,但是使用$keys上面创建的I来标识要插入的位置?

喜欢:

$arr['one']['two']['three']['four'] = 'value';

对不起,如果问题令人困惑,但我不知道如何更好地解释它

Mar*_*iot 14

这有点不重要,因为你想要嵌套,但它应该是这样的:

function insert_using_keys($arr, $keys, $value){
    // we're modifying a copy of $arr, but here
    // we obtain a reference to it. we move the
    // reference in order to set the values.
    $a = &$arr;

    while( count($keys) > 0 ){
        // get next first key
        $k = array_shift($keys);

        // if $a isn't an array already, make it one
        if(!is_array($a)){
            $a = array();
        }

        // move the reference deeper
        $a = &$a[$k];
    }
    $a = $value;

    // return a copy of $arr with the value set
    return $arr;
}
Run Code Online (Sandbox Code Playgroud)


FtD*_*Xw6 6

$string = 'one/two/three/four';
$keys = explode('/', $string);
$arr = array(); // some big array with lots of dimensions
$ref = &$arr;

while ($key = array_shift($keys)) {
    $ref = &$ref[$key];
}

$ref = 'value';
Run Code Online (Sandbox Code Playgroud)

这是做什么的:

  • 使用变量,$ref来跟踪对当前维度的引用$arr.
  • 一次循环$keys一次,引用$key当前引用的元素.
  • 将值设置为最终引用.

  • 当'$ arr`不是数组时,你的解决方案"会失败",还有一些其他情况.防弹错误检查不是正确答案的先决条件. (2认同)