我有这个代码:使用此代码,我加载本地 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数组..
1 回答
Smart猫小萌
TA贡献1911条经验 获得超7个赞
使用array_merge_recursive()
.
<?php
$_GET = [
'myserver' => [
'state'=>'10'
]
];
$existingJson = '{
"key1": "val1",
"key2": "val2"
}';
$array = json_decode($existingJson, true);
$newArray = array_merge_recursive($array, $_GET);
print_r($newArray);
结果:
Array
(
[key1] => val1
[key2] => val2
[myserver] => Array
(
[state] => 10
)
)
https://3v4l.org/i1YvC
- 1 回答
- 0 关注
- 143 浏览
添加回答
举报
0/150
提交
取消