我有一个问题。
我写了一个函数来更新我的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;
}
我也创建了一个更新键的函数。但问题是,如果我执行
update('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...
}
我有一个工作函数,但并不是很好。我知道索引的最大值只能为三,所以我计算了爆炸的 $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数组,所以没有问题 :)
$this->config['database']['host']
的值,但你的函数正在更新$this->config['database']到新值,这意味着它覆盖了其他子数组,如主机、用户和密码。我希望你明白我的意思,我的英语不是很好:s - user5629061is_array($value)
来检查值是否为数组,并以递归方式调用该函数来解决你面临的维度问题。 - Bas van Stein