1

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.

Hiurako
  • 177
  • 2
  • 10

3 Answers3

2

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;
    }
}
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

There's and array_filter function in php, which is perfect for your case.

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

Btw. your code don't work, because you unset only the current loop var and not the actual array item. If you pass an key to the foreach, you could also delete the actual array item.

foreach ($posts as $key => $post) {
    if ($post->id == $id) {
        unset($posts[$key]);
    }
}
// save json
Philipp
  • 15,377
  • 4
  • 35
  • 52
1

It seems your unset is not working because you don't pass $post it by reference. I would do it with array_filter tho.

function deleteById($json, $id) {
    return json_encode(array_filter(json_decode($json, true), 
        function($e) use ($id) {
          return $e['id'] != $id;
        }
    ));
}
bnorb
  • 138
  • 5