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

php更改多维数组的值

发布时间:2020-12-13 15:59:37 所属栏目:PHP教程 来源:网络整理
导读:我遇到了问题. 我创建一个函数来更新我的config.json文件. 问题是,我的config.json是一个多维数组.要获取键的值,我使用此函数: public function read($key){ $read = explode('.',$key); $config = $this-config; foreach ($read as $key) { if (array_key_
我遇到了问题.

我创建一个函数来更新我的config.json文件.
问题是,我的config.json是一个多维数组.要获取键的值,我使用此函数:

public function read($key)
{
    $read   = explode('.',$key);
    $config = $this->config;
    foreach ($read as $key) {
        if (array_key_exists($key,$config)) {
            $config = $config[$key];
        }
    }

    return $config;
}

我还做了一个更新密钥的功能.但问题是如果我进行更新(‘database.host’,’new value’);它不会只更新该键,但它会覆盖整个数组.

这是我的更新功能

public function update($key,$value)
{
    $read   = explode('.',$key);
    $config = $this->config;
        foreach ($read as $key) {
        if (array_key_exists($key,$config)) {
            if ($key === end($read)) {
                $config[$key] = $value;
                                     }
                $config = $config[$key];
                                              }
                                }
        print_r( $config );
}

我的config.json看起来像这样:

{
    "database": {
        "host": "want to update with new value","user": "root","pass": "1234","name": "dev"
    },some more content...
}

我有一个工作功能,但那不是很好.我知道索引的最大值只能是3,所以我计算爆炸的$key并更新值:

public function update($key,$value)
{
    $read  = explode('.',$key);
    $count = count($read);
        if ($count === 1) {
        $this->config[$read[0]] = $value;
    } elseif ($count === 2) {
        $this->config[$read[0]][$read[1]] = $value;
    } elseif ($count === 3) {
        $this->config[$read[0]][$read[1]][$read[3]] = $value;
    }
        print_r($this->config);
}

只是要知道:变量$this-> config是我的config.json解析为php数组,所以没有错误:)

解决方法

在我更好地阅读了你的问题之后,我现在明白你想要什么,而你的阅读功能虽然不是很清楚,但效果很好.

您可以通过引用和分配来改进您的更新.循环索引并将新值分配给数组的正确元素.

以下代码的作用是使用引用调用将完整的配置对象分配给临时变量newconfig,这意味着每当我们更改newconfig变量时,我们也会更改this-> config变量.
多次使用这个“技巧”,我们最终可以将新值分配给newconfig变量,并且由于通过引用分配调用,应该更新this-> config对象的正确元素.

public function update($key,$key);
    $count = count($read);

    $newconfig = &$this->config; //assign a temp config variable to work with
    foreach($read as $key){
        //update the newconfig variable by reference to a part of the original object till we have the part of the config object we want to change.
        $newconfig = &$newconfig[$key];
    }
    $newconfig = $value;


    print_r($this->config);
}

(编辑:李大同)

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

    推荐文章
      热点阅读