Removing a json array object with PHP


#1

I'm trying to remove single objects from a json array, but when I attempt to delete the DOM object rectangle (each of which represents an array object), then process.php ends up making a copy of the array and appending it to the original array.

When I click the delete button (class rectangle-delete), I change the deleteStatus hidden input value to delete which I'm trying to pick up in process.php. This is the particular bit in process.php that I thought would do the trick:

foreach($arr_data as $key => $value) {
if($value->value != "delete") {
$arr_data[] = $value;
}
}

Here is the entire process.php:

<?php

   //$myFile = "data/data.json";
   $filename = $_POST['store-template-name'];
   $myFile = "data/" . $filename;
   $arr_data = array(); // create empty array

  try
  {
	   //Get form data
	   $formdata = array(
	   	  'ID'=> $_POST['ID'],
	   	  'attributeName'=> $_POST['attributeName'],
          'deleteStatus'=> $_POST['deleteStatus'],
	      '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);
	   $updateKey = null;
	   foreach ($arr_data as $k => $v) {
		    if ($v['ID'] == $formdata['ID']) {
		        $updateKey = $k;
		    }
		}
       //  delete object in json
       foreach($arr_data as $key => $value) {
          if($value->value != "delete") {
              $arr_data[] = $value;
          }
       }
		if ($updateKey === null) {
		    array_push($arr_data,$formdata);
		} else {
		    $arr_data[$updateKey] = $formdata;
		}

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

#2

Maybe this is a "by reference" thing?

http://php.net/manual/en/control-structures.foreach.php

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.


#3

Thanks for the reply. How would my codeblock look with the ampersand? Like the following?

foreach($arr_data as $key => &$value) {
if($value->value != "delete") {
$arr_data[] = $value;
}
}


#4

In Process.php after pushing updates to the form, this worked for me:

foreach($arr_data as $elementKey => $element) {
		    foreach($element as $valueKey => $value) {
		        if($valueKey == 'deleteStatus' && $value == 'delete'){
		            //delete this particular object from the $array
		            unset($arr_data[$elementKey]);
		        } 
		    }
		}

#5

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.