我使用此 PHP 文件保存表单数据,并且每次提交表单时它都会附加数据。我只需要一种方法来根据表单 ID 字段中的 ID 覆盖数组中的特定对象。
例如,我想将 ID 147 表单中的 attributeType 值更改为其他值,然后提交,并使其仅覆盖第一个对象(而不是附加 ID 147 的另一个对象)。
我尝试过使用 array_splice() 方法但没有成功。
流程.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";
}
?>
数据.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"}]
需要循环遍历现有的数据集,检查该ID是否已经存在,如果存在,记下索引并更新记录。如果 ID 不存在,则追加数组。
(如果 ID 相同,此解决方案会更新整个记录)
<?php
$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"}]';
$formdata = array(
'ID'=> 147,
'attributeName'=> 'PatientName',
'valueX'=> 55,
'valueY'=> 60,
'valueHeight'=> 55,
'valueWidth'=> 60,
'valueURL'=> 'www.test.com',
'attributeType'=> 'incomplete'
);
$arr = json_decode($json, true);
$updateKey = null;
foreach ($arr as $k => $v) {
if ($v['ID'] == $formdata['ID']) {
$updateKey = $k;
}
}
if ($updateKey === null) {
array_push($arr_data,$formdata);
} else {
$arr[$updateKey] = $formdata;
}