加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 动态数组键

发布时间:2020-12-13 13:02:41 所属栏目:PHP教程 来源:网络整理
导读:我有一个像这样的字符串: $string =’一/二/三/四’; 把它变成一个数组: $keys = explode(‘/’,$string); 该数组可以包含任意数量的元素,如1,2,5等. 如何为多维数组指定某个值,但是使用我在上面创建的$键来标识要插入的位置? 喜欢: $arr [‘one’] [‘t
我有一个像这样的字符串:

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

把它变成一个数组:

$keys = explode(‘/’,$string);

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

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

喜欢:

$arr [‘one’] [‘two’] [‘three’] [‘four’] =’value’;

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

这有点不重要,因为你想要嵌套,但它应该是这样的:
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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读