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条)

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?