我想使用 PHP 更新一個 json 檔案
$Folder = $_REQUEST['Folder']; // "wwwroot/JSON/"
$File = $_REQUEST['File']; // "JSONOriginalFile.json"
$NewJSONValue = $_REQUEST['JsonValue']; // "NewValue"
$JsonObject = json_decode($_REQUEST['JsonObect']); // ["Layer1","Layer2","ObjectToUpdate"]
$JSON = file_get_contents($Folder.$File);
$JSON = json_decode($JSON);
這里的目標是運行一些動態的東西
$JSON->Layer1->Layer2->ObjectToUpdate = $NewJSONValue;
$JSON= json_encode($JSON);
file_put_contents('../../'.$Folder.'/'.$File, $JSON);
但是我不能進入動態嵌套層例如:我可以嘗試使用相同的“應用程式”來更新 ["Layer1","ObjectToUpdate"] 或 ["Layer1","Layer2","Layer3","ObjectToUpdate" ] 或只是 ["ObjectToUpdate"] 等。
目標是讓陣列被轉置為嵌套搜索,最后一個陣列物件是要更新的物件。
php中是否存在類似的東西?
即使運行類似的東西
$JsonString = "$JSON";
foreach($JsonObject as $Object) {
$JsonString .= "->".$Object;
}
它沒有幫助。有人有解決方案嗎?
uj5u.com熱心網友回復:
您可以使用花括號語法來訪問物件方法{$name_of method}(“像”您使用方括號表示陣列):
$str_json = '{"store":{"book":{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95}}}';
$tag_to_edit = [ "store", "book", "author"];
$new_value = "A. Einstein";
$obj_json = json_decode($str_json);
$element_to_edit = $obj_json;
foreach($tag_to_edit as $t)
$element_to_edit = &$element_to_edit->{$t};
$element_to_edit = $new_value;
die($obj_json->store->book->author); // A. Einstein
這將起作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/492846.html
下一篇:修改ajax資料回傳
