动态数组键 [英] Dynamic array keys

查看:39
本文介绍了动态数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串:

I have a string like this:

$string = '一/二/三/四';

我把它变成一个数组:

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

这个数组可以有任意数量的元素,比如 1、2、5 等

This array can have any number of elements, like 1, 2, 5 etc.

如何给多维数组赋值,但使用我上面创建的$keys来确定插入的位置?

How can I assign a certain value to a multidimensional array, but use the $keys I created above to identify the position where to insert?

喜欢:

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

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

Sorry if the question is confusing, but I don't know how to explain it better

推荐答案

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

This is kind of non-trivial because you want to nest, but it should go something like:

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;
}

这篇关于动态数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆