需要使用PHP替换数组中具有匹配ID的对象

时间:2017-12-01 22:30:13

标签: php arrays json

我使用这个PHP文件保存表单数据,并且每次提交表单时它都会将数据附加到正确的位置。我只需要一种方法来根据表单ID字段中的ID覆盖数组中的特定对象。

例如,我想将ID 147表单中的 attributeType 值更改为其他值,提交,并让它仅覆盖第一个对象(而不是附加另一个对象) ID为147的对象。

我尝试过使用array_splice()方法,但没有成功。

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";
   }

?>
&#13;
&#13;
&#13;

data.json

&#13;
&#13;
[{"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"}]
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您需要遍历现有数据集,检查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;
}