通过PHP更新JSON文件
问题描述:
我想通过php更新JSON文件,但当前代码正在做的是追加新对象而不是替换它。下面是JSON的一个片段:通过PHP更新JSON文件
[
{
"id": 3,
"title": "SOME MODS",
"date": "Aug\/Sept 2017",
"done": "yes",
"files changed": {
"1": "index.html",
"2": "style.css"
},
"backend changes\/additions": {
"1": "added some stuff"
},
"additions": {
"1": "logo.jpg"
}
}
]
基本上就是我想要做的是点击按钮调用AJAX功能打一个PHP文件。然后检查通过的ID是否与来自JSON文件的ID匹配,然后更新“完成”属性...如果没有,则是,如果是,则将其设为否。
这里是我的PHP代码:
if (isset($_POST['comp'])) {
$newObj = $_POST['comp'];
$jsonFile = file_get_contents('data.json');
$temp = json_decode($jsonFile, true);
$tempArray;
foreach($temp as $e){
if($e['id'] == $newObj) {
if ($e['done'] === 'no'){
$e['done'] = 'yes';
$tempArray = $e;
} else {
$e['done'] = 'no';
$tempArray = $e;
}
}
}
$temp[] = $tempArray;
$final_data = json_encode($temp, JSON_PRETTY_PRINT);
file_put_contents('data.json', $final_data);
print_r($temp);
但正如我所提到的,因为它代表所有它做的是插入一个新的对象,而不是取代的。我需要更改什么才能使此功能起作用?
谢谢大家。
-S
答
你想传递$e
by reference在你的foreach:
<?php
// this originally comes from file
$json = <<<EOT
[
{
"id": 3,
"title": "SOME MODS",
"date": "Aug\/Sept 2017",
"done": "yes",
"files changed": {
"1": "index.html",
"2": "style.css"
},
"backend changes\/additions": {
"1": "added some stuff"
},
"additions": {
"1": "logo.jpg"
}
}
]
EOT;
$temp = json_decode($json, true);
$newObj=3; // this is only here for testing
// here's the trick: the & before $e
foreach($temp as &$e){
if($e['id'] == $newObj) {
if ($e['done'] === 'no'){
$e['done'] = 'yes';
} else {
$e['done'] = 'no';
}
}
}
$final_data = json_encode($temp, JSON_PRETTY_PRINT);
file_put_contents('data.json', $final_data);
这样,你不需要另一个阵列,可以节省$temp
回你的JSON文件。
简短的说明(裂纹,请指正):
在你的foreach PHP使得$ E的副本,所以你必须把它写回 - 因为你已经试过。
当您通过引用传递它时,您将处理原始项目$ e,而不是副本。这样你可以直接操纵它。
$ temp []附加到$ temp。去掉 []。 – endrju
here'$ temp [] = $ tempArray;'你正在添加新的内容。 – Jeff
我想你想通过[reference](http://php.net/manual/en/language.references.pass.php)进行foreach。通过这种方式,您可以遍历数组并更改要更改的值。 – Jeff