I'm saving form data with this PHP file, and it appends the data fine each time I submit the form. I just need a way to overwrite specific objects in the array based on the ID in the ID field of the form.
For example, I'd like to change the attributeType value in the form for ID 147 to a different value, submit, and have it only overwrite the first object (rather than appending another object with ID 147).
I've tried to use the array_splice() method but haven't had success.
Process.php
<?php
$myFile = "data/data.json";
$arr_data = array(); // create empty array
try
{
//Get form data
$formdata = array(
'ID'=> $_POST['ID'],
'attributeName'=> $_POST['attributeName'],
'valueX'=> $_POST['valueX'],
'valueY'=> $_POST['valueY'],
'valueHeight'=>$_POST['valueHeight'],
'valueWidth'=> $_POST['valueWidth'],
'valueURL'=> $_POST['valueURL'],
'attributeType'=> $_POST['attributeType']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
// Push user data to array
array_push($arr_data,$formdata);
//Convert updated array to JSON
$jsondata = json_encode($arr_data);
//write json data into data.json file
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
data.json
[{"ID":"147","attributeName":"PatientName","valueX":"50","valueY":"50","valueHeight":"50","valueWidth":"50","valueURL":"www.test.com","attributeType":"incomplete"},{"ID":"148","attributeName":"Complaints","valueX":"50","valueY":"50","valueHeight":"50","valueWidth":"50","valueURL":"www.test.com","attributeType":"missing"}]