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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)