donglu7816 2018-05-03 20:30
浏览 35
已采纳

如何使用基于ID的PHP从json文件中删除对象

Hi i wonder how i can delete data from json file based on id if my json struct looks like that:

[
    {
        "id": 1,
        "title": "a",
        "decription": "b"
    },
    {
        "id": 2,
        "title": "c",
        "decription": "d"
    }
]

What I've tried so far:

     if (isset($_POST['delete_post'])) 
     {

        $id = $_POST['post-id'];

        if(empty($id)) return;

        $posts = json_decode(file_get_contents('posts.json'));

        foreach ($posts as $post) 
        {
            if ($post->id == $id) 
            {
                unset ($post);
            }
            $save = json_encode($posts, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            file_put_contents('posts.json', $save);
        }

     }

And i literally stuck at this ponint.

</div>
  • 写回答

3条回答 默认 最新

  • doufu7464 2018-05-03 20:41
    关注

    unset $post doesn't remove the element from the array, it just unsets that temporary variable.

    After unsetting the element you need to use array_values() to get a new array with consecutive indexes. If there's a gap in the indexes, json_encode() will encode it as an object.

    You also should break out of the loop once you find the element to delete and rewrite the file.

        foreach ($posts as $i => $post) 
        {
            if ($post->id == $id) 
            {
                unset ($posts[$i]);
                $save = json_encode(array_values($posts), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
                file_put_contents('posts.json', $save);
                break;
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条