我有这个代码:
使用此代码,我加载本地 json 文件并尝试 array_replace,如果存在则替换,如果不存在则添加
<?php
// check if all form data are submitted, else output error message
$count = count(explode('&', $_SERVER['QUERY_STRING']));
if ( $count > 0 ) {
$string = file_get_contents("testconfig.json");
$json_a = json_decode($string, true);
$replaced_array = array_replace( $json_a, $_GET );
$jsondata = json_encode($replaced_array, JSON_PRETTY_PRINT);
if(file_put_contents('testconfig.json', $jsondata)) echo 'OK';
else echo 'Unable to save data in "testconfig.json"';
}
else
{ echo 'Form fields not submitted'; }
?>
假设现有的 json 是这样的:
{
"key1": "val1",
"key2": "val2"
}
status.php?myserver[state]=10 并会导致这样的结果:
{
"key1": "val1",
"key2": "val2",
"myserver": {
"state": 10
}
}
但是然后我想像myserver这样添加到元素: status.php?myserver[mem]=3并且如果存在的话会添加到数组,如下所示:
{
"key1": "val1",
"key2": "val2",
"myserver": {
"state": 10,
"mem": 3
}
}
但我的代码替换了整个myserver数组..
Smart猫小萌