We enter data in JSON

$file = file_get_contents('./data.json'); $formdata = json_decode($file,TRUE); unset($file); $formdata []= array( 'title' => $title, 'data' => $data, 'author' => $author, 'message' => $message ); file_put_contents('./data.json',json_encode($formdata)); unset($formdata); 

Get the array:

 [{"title":"1","data":"1","author":"1","message":"1"},{"title":"12","data":"12","author":"12","message":"12"},{"title":"123","data":"123","author":"123","message":"123"}] 

When deleting a single object:

 $filedata = json_decode(file_get_contents('./data.json'), true); $index = array_count_values([$_POST['index']]); $array_number = key($index); unset($filedata[$array_number]); file_put_contents('./data.json', json_encode($filedata)); 

besides deletion, the array is "transformed" into

 {"0":{"title":"1","data":"1","author":"1","message":"1"},"2":{"title":"123","data":"123","author":"123","message":"123"}} 

and after that I can’t add more elements to it (the deletion is normal).

How to make it so that when deleting elements of an array, it does not change the view, but simply removes one element of the array? An example (it is necessary to look like an array after deleting [1] -th element):

 [{"title":"1","data":"1","author":"1","message":"1"},{"title":"123","data":"123","author":"123","message":"123"}] 

    2 answers 2

     file_put_contents('./data.json',json_encode(array_values($formdata))); 

    You had the keys 0, 1 and 2 in the PHP array after unpacking json_decode . After deleting an element, the keys 0 and 2 become steel. json_encode does not know if you need keys in the future and tries to save them - but you cannot set keys in the JSON array, so json_encode decides to write an object, not an array. array_values you can create a copy of a PHP array with simple numeric sequential keys, and such an array can easily be written as a JSON array.

      Can be deleted with array_splice() . This function renumbers indices, so you will have an array in JSON.

      That is, instead of:

       unset($filedata[$array_number]); 

      need to write:

       array_splice($filedata, $array_number, 1); 

      If it is necessary to delete several elements, problems may arise during deletion (since the index of the next element to be deleted may change). In this case, you can delete the function unset() , and then take an array using the function array_values()