我有這個代碼:使用此代碼,我加載本地 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 關注
- 191 瀏覽
添加回答
舉報
0/150
提交
取消