我正在尝试使用PHP表单来更新JSON文件,但是当我编辑该文件的某个字段时,它会创建该条目的副本,但会显示更新的信息。例如:
[
{"toolName":"tool1", "url":"https://google.com/", "phase":"None"},
{"toolName":"tool2", "url":"http://yahoo.com/", "phase":"None"},
{"toolName":"tool3", "url":"http://bing.com/", "phase":"None"}
]
如果在提交时,PHP表单想要更改"阶段"对于" tool1",它会添加一个包含更新的新条目。喜欢:
[
{"toolName":"tool1", "url":"https://google.com/", "phase":"None"},
{"toolName":"tool2", "url":"http://yahoo.com/", "phase":"None"},
{"toolName":"tool3", "url":"http://bing.com/", "phase":"None"},
{"toolName":"tool1", "url":"https://google.com/", "phase":"NewPhase"}
]
如何避免这种情况?我在更新时使用数组中工具的索引作为标识符,因此我目前的解决方案是:
$toolId = $_POST['tool-id'];
$toolName = $_POST['tool-name'];
$toolUrl = $_POST['tool-url'];
$toolPhase = $_POST['tool-phase'];
$data = file_get_contents("../assets/js/tools.json");
$json_data = json_decode($data, true);
$json_data[$toolId]->toolName = $toolName;
$json_data[$toolId]->url = $toolUrl;
$json_data[$toolId]->phase = $toolPhase;
$json_data = array_values($json_data);
file_put_contents("../assets/js/tools.json", stripslashes(json_encode($json_data)));
**注意:提交表单时,我使用的是Bootstrap模式,所以我只发送当前可见工具的数据(即索引" toolId"的工具),所以我做不要遍历整个JSON文件。
答案 0 :(得分:0)
此行中的true语句指示PHP返回数组
$json_data = json_decode($data, true);
但是,这些行会创建一个对象
$json_data[$toolId]->toolName = $toolName;
$json_data[$toolId]->url = $toolUrl;
$json_data[$toolId]->phase = $toolPhase;
如果你将它们更改为它应该可以正常工作
$json_data[$toolId]['toolName'] = $toolName;
$json_data[$toolId]['url'] = $toolUrl;
$json_data[$toolId]['phase'] = $toolPhase;