dongyin2643
2015-01-18 19:14
浏览 29

使用PHP从JSON中删除

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/"
        }
      ]
    },

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用项目的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'); 
} 
} 
} 
   
 
 

我正在使用的REST客户端提供了204但是当我查看时 我的JSON文件,该项目仍然存在。

知道我做错了吗?

编辑

JSON看起来像这样

  {
“items”:[
 {
“id”:1,
“title”:“title”,
“ 艺术家“:”艺术家“,
”流派“:”流派“,
”链接“:[
 {
”rel“:”self“,
”href“:”link / webservice / music /  1“
},
 {
”“rel”:“collection”,
“href”:“link / webservice /”
} 
] 
},
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxin1956 2015-01-18 19:24
    已采纳

    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');
            }
        }
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题