在 PHP 中修改后覆盖 json


Overwrite a json after modification in PHP

我用这段代码在我的json中进行修改:

$id = "hotel_name";
$value ="My Hotel";
$json = json_decode(file_get_contents('datas.json'));
$datas = $json->datas;
foreach ($datas as $category => $data) {
    foreach ($data as $element) {
        if($element->id==$id) {
            $datas->$category->$element->$id = $value;
        }
    }
}
$newJson = json_encode($element);
file_put_contents('datas.json', $newJson);

但它并没有将所有内容都放进去。

请问如何解决?

<小时 />

我的 json 有以下内容:

{
    "datas": {
        "General": [
            {
                "field": "hotel_name",
                "name": "My Hotel name"
            }
        ]     
    }
}

您正在访问$element变量,该变量仅包含您最内部的数据

{
    "field": "hotel_name",
    "name": "My Hotel name"
}

如果你想要更多的数据,你必须用新更新的$element变量重新分配最外层的$datas变量和子变量。我建议创建一个空变量来存储新数据,而不是更改原始副本。

你应该对数据进行编码,而不仅仅是最后一个元素,对吧?

// before
$newJson = json_encode($element);
// after
$newJson = json_encode($datas);

顺便说一下,您可能会发现,如果将数据转换为数组而不是对象,则更容易处理数据。

$json = json_decode(file_get_contents('datas.json'), true);