0

I can successfully delete elements of a JSON array with PHP, but I cannot understand why the JSON array changes syntax after deleting an element that's not the last one.

So, here's my User.json file:

[ 
    {
        "id": "kS79BhPx"
    },
    {
        "id": "ycC7km7A"
    },
    {
        "id": "hgF5D4es"
    }
]

Here's my delete.php script:

$className = "Users";

// get the index
$index = (int)$_GET['index'];

//fetch data from json
$data = file_get_contents($className. '.json');
$data_array = json_decode($data, true);

// delete the row with the index
unset($data_array[$index]);

//encode back to json
$data = json_encode($data_array, JSON_PRETTY_PRINT);
file_put_contents($className. '.json', $data);

So, if I go to the following URL, just to test my php function:

https://example.com/delete.php?index=0

The script successfully deletes the first element of the JSON array, but then it changes into this:

{
    "1": {
        "id": "ycC7km7A"
    },
    "2": {
        "id": "hgF5D4es"
    }
}

Instead, if I set https://example.com/delete.php?index=2 - so I want to delete the last array's element - it saves it as follows:

[
    {
        "id": "kS79BhPx"
    },
    {
        "id": "ycC7km7A"
    }
]

This last result is what I need to achieve all the times I delete an element because I need the JSON array syntax to stay as [...], not as {...}.

What am I doing wrong in my PHP script?

Frank Eno
  • 2,581
  • 2
  • 31
  • 54

1 Answers1

2

Using unset() on an array (associative or not) in PHP will preserve the existing keys making the array associative. You need to reindex the array after using unset():

// delete the row with the index
unset($data_array[$index]);
$data_array = array_values($data_array);
Jim
  • 3,210
  • 2
  • 17
  • 23