0

I want to delete a record from JSON, by changing the status to DELETE before submitting.

JSON:

{
John Taylor: {
  name: "John Taylor",
  title: "Director",
  photo_url: "Creative-JohnTaylor",
  status: "Current"
},

John Taylor 2: {
  name: "John Taylor 2",
  title: "Photographer",
  photo_url: "Creative-JohnTaylor2.jpg",
  status: "DELETE"
}

I read from JSON just fine:

$data_url = 'data.json';
$data_json = file_get_contents($data_url);
$data_array = json_decode($data_json, true);
//plus a bunch of _GET stuff here...
...

// then write to JSON like so
$data[$name] = array(
    'name' => $name,
    'title' => $title,
    'photo_url' => $photo_url,
    'status' => $status
    );

//EDIT - this is my feeble attempt
if($status == 'DELETE'){
    unset($data[$name]);
};
//END EDIT

// merge and write array to json    
$data_array = array_merge($data_array, $data);
file_put_contents('data.json', json_encode($data_array, JSON_FORCE_OBJECT));

But can't figure out how to delete the record...

3
  • I don't see an attempt at manipulating $data_array after you've json_decode'd the data to delete the keys with "delete" status. You also don't need the JSON_FORCE_OBJECT, as you are forcing data_array to be an associative array in your decode call. Commented Apr 8, 2015 at 22:02
  • ok, I put my initial best attempt in there. didn't even dent it though... Commented Apr 9, 2015 at 16:59
  • Marko's answer looks good. As he points out, you'll need to go through each item in data (foreach), check if the status for that item is set to DELETE, and if so, remove that item from data. Commented Apr 10, 2015 at 0:33

1 Answer 1

2

As I can see, you are trying to delete part of json in php.

You could use this code:

foreach($data as $key=>$val){
   // check status
   if ($val["status"]=="DELETE"){
      // this deletes record from array
      unset($data[$key]);
   }
}

file_put_contents('data.json', json_encode($data, JSON_FORCE_OBJECT));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.