dongyin2643 2015-01-18 19:14
浏览 40
已采纳

使用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/"
        }
      ]
    },
  • 写回答

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');
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。