简体   繁体   English

无法在 PHP 中修改 JSON 文件

[英]Failed to modify JSON file in PHP

This is my json.json file content这是我的 json.json 文件内容

{
    "Title": "Hello World",
    "Inputs": [
             {
               "Id": "1",
               "Title": "One"
             },
             {
               "Id": "15",
               "Title": "Fifteen"
             }
          ]
 }

I am trying to modify it as the follows -我正在尝试将其修改如下 -

$text = file_get_contents("json.json");
$json = json_decode($text,true);

foreach($json["Inputs"] as $input){

    if($input["Id"]== "15"){
        $input["Title"] = "This is from me.";
    }       
}

$new = json_encode($json);
file_put_contents('json.json', $new);

But the file is not being updated.但是文件没有被更新。

Any idea?任何的想法?

Your JSON in the example is improperly formatted, but the issue you are having is that you do not set the title in the original array.您在示例中的 JSON 格式不正确,但您遇到的问题是您没有在原始数组中设置标题。 You change the copy that is passed to the foreach loop.您更改传递给 foreach 循环的副本。

Change your foreach loop to this and your changes should be shown:将您的 foreach 循环更改为此,您的更改应显示:

foreach($json["Inputs"] as $key => $input){
    if($input["Id"]== "15"){
        $json["Inputs"][$key]["Title"] = "This is from me.";
    }
}

The foreach loop takes the value by reference, so changing the $json['Inputs'] will change the original value, whereas changing $input modifies the copy that is passed to the loop, and does not change the original json data. foreach循环通过引用获取值,因此更改$json['Inputs']将更改原始值,而更改$input会修改传递给循环的副本,并且不会更改原始json数据。 There are ways to pass by reference to the foreach loop, but this seems like a simpler solution.有多种方法可以通过引用传递给foreach循环,但这似乎是一个更简单的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM