I am trying to update a JSON file via php, but what the current code is doing is appending the new object instead of replacing it. Here's a snippet of the 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"
}
}
]
Basically what I want to do is on click of a button call an AJAX function to hit a php file. Then check to see if the passed id matches an id from the JSON file, then updated the "done" property... if no make it yes, if yes make it no.
Here's my PHP code:
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 );
But as I mentioned, as it stands all it is doing is inserting a new Object instead of replacing. What do I need to change to make this functionality work?
Thank you all.
-S