0

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/"
        }
      ]
    },
1
  • Have a look at the first example in the foreach docs You need to reference it as foreach ($json->items as &$item) by reference &$item to be able to modify it. Commented Jan 18, 2015 at 19:24

1 Answer 1

2

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');
        }
    }
}
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.