使用PHP从JSON中删除

时间:2015-01-18 19:14:36

标签: php json rest unset

我尝试使用项目的ID从JSON文件中删除项目。 这是我用来执行此操作的代码。

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

我使用的RESTclient给出了204但是当我查看我的JSON文件时,该项仍然存在。

知道我做错了吗?

修改

JSON看起来像这样

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

1 个答案:

答案 0 :(得分:2)

在foreach循环中,您获得的数组元素的副本在某些方面不会影响原始数组。

您需要使用原始数组取消引用数组项,或者通过引用将其传递给循环。

以下应该有用,我想:

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