【问题标题】:How can i delete object from json file with PHP based on ID如何使用基于 ID 的 PHP 从 json 文件中删除对象
【发布时间】:2018-10-14 06:15:48
【问题描述】:

您好,如果我的 json 结构看起来像这样,我想知道如何根据 id 从 json 文件中删除数据:

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

到目前为止我已经尝试过:

     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);
        }

     }

我确实卡在了这个节点上。

【问题讨论】:

  • 嗨,您需要展示一些努力/代码,然后人们会提供帮助!也许先尝试将其放入数组中?
  • 哎呀,我的错误我在没有 PHP 代码的情况下保存了,更新了。
  • 对我来说看起来不错。我会试试看。你只是得到一些语法错误吗?检查日志。概念步入正轨。
  • 不,没有收到任何错误,但它根本不会删除任何内容

标签: php


【解决方案1】:

unset $post 不会从数组中删除元素,它只是取消设置该临时变量。

取消设置元素后,您需要使用array_values() 来获取具有连续索引的新数组。如果索引中有间隙,json_encode() 会将其编码为对象。

一旦找到要删除和重写文件的元素,您也应该跳出循环。

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】:

    您的 unset 似乎不起作用,因为您没有通过引用传递 $post 它。 我会用 array_filter 来做。

    函数 deleteById($json, $id) {
        返回 json_encode(array_filter(json_decode($json, true),
            函数($e)使用($id){
              返回 $e['id'] != $id;
            }
        ));
    }

    【讨论】:

      【解决方案3】:

      php中有array_filter函数,非常适合你的情况。

      // ...
      $posts = array_filter($posts, function($item) use ($id) {
          return $item != $id;
      });
      // ...
      

      顺便说一句。你的代码不起作用,因为你只取消了当前循环变量而不是实际的数组项。如果将键传递给 foreach,则还可以删除实际的数组项。

      foreach ($posts as $key => $post) {
          if ($post->id == $id) {
              unset($posts[$key]);
          }
      }
      // save json
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-15
        • 2021-07-08
        • 1970-01-01
        • 1970-01-01
        • 2017-03-25
        • 2021-08-21
        • 2021-03-24
        相关资源
        最近更新 更多