亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP 替換 json 中的元素

PHP 替換 json 中的元素

PHP
蝴蝶不菲 2023-07-15 15:46:40
我有這個代碼:使用此代碼,我加載本地 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


查看完整回答
反對 回復 2023-07-15
  • 1 回答
  • 0 關注
  • 191 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號