user3182261
user3182261

Reputation: 271

Delete from JSON with PHP

I'm trying to delete an item from a JSON file using the id of the item. This is the code I'm using to do so.

 if($id){
    header('Content-Type: application/json');
    $id = $_GET['id'];
    $file = file_get_contents("data.json");
    $json = json_decode($file);


    foreach ($json->items as $item) {
        if ($item->id == $id) {
                        unset($item);
                        file_put_contents('data.json', json_encode($json));
                        header('HTTP/1.1 204 No Content');
        }
    }
}

The RESTclient I'm using gives the 204 but when I look in my JSON file, the item is still there.

Any idea what I'm doing wrong?

EDIT

JSON looks like this

{
  "items": [
    {
      "id": 1,
      "title": "title",
      "artist": "artist",
      "genre": "genre",
      "links": [
        {
          "rel": "self",
          "href": "link/webservice/music/1"
        },
        {
          "rel": "collection",
          "href": "link/webservice/"
        }
      ]
    },

Upvotes: 0

Views: 1487

Answers (1)

Johann Bauer
Johann Bauer

Reputation: 2606

Inside a foreach-loop the copy of the array element you've got does not affect the original array in some ways.

You need to dereference the array item using the original array or pass it to the loop by reference.

The following should work, I guess:

if($id){
    header('Content-Type: application/json');
    $id = $_GET['id'];
    $file = file_get_contents("data.json");
    $json = json_decode($file);


    foreach ($json->items as $key => $item) {
        if ($item->id == $id) {
                        unset($json->items[$key]);
                        file_put_contents('data.json', json_encode($json));
                        header('HTTP/1.1 204 No Content');
        }
    }
}

Upvotes: 2

Related Questions