微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php更改多维数组的值

我遇到了问题.

我创建一个函数来更新我的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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐