Reputation: 267
Disclaimer: I'm somewhat new to PHP. 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";
}
?>
Upvotes: 0
Views: 598
Reputation: 579
Maybe you are trying to filter your $arr_data
array to remove the entities when the value is "delete", Am I right? If yes, you could try this.
foreach($arr_data as $key => $value) {
if($value->value != "delete") {
$arr_data[] = $value;
}else{
unset($arr_data[$key]);
}
}
or this
$arr_data = array_filter($arr_data, function($value){
return $value->value != "delete";
});
Upvotes: 1