John Lotacs
John Lotacs

Reputation: 1254

Deleting index of JSON Array in PHP, creating string version of index?

I'm trying to get a sampling of PHP to work but I'm having a bit of an issue.

Initially, if I just create JSON data and save it to a file the structure looks as follows

[{"id":"519d4434e39ef","title":"event 3","start":"1369108800","end":"1369195199"},

{"id":"519d4430333c1","title":"event 2","start":"1368676800","end":"1368763199"},

{"id":"519d442a2b29c","title":"event 1","start":"1368504000","end":"1368590399"}]

That is created with the following code sample

$msg = array('id' => uniqid(),
             'title' => $_POST['title'],
             'start' => $_POST['start'],
             'end' => $_POST['end']);


$data = get_data();
array_unshift($data, $msg);         
file_put_contents($data_file, json_encode($data))

But, if I try to delete an item in that set of JSON data with this

$deleteId  = $_POST['id'];
$data = get_data();
$index = -1;
for($i=0; $i < count($data); $i++){
  if($data[$i]['id'] == $deleteId){
  $index = $i;
  break;
  } 
}

if($index != -1){
  unset($data[$index]);
}

file_put_contents($data_file, json_encode($data))

The file ends up looking like the following

{"0":{"id":"519d4434e39ef","title":"event 3","start":"1369108800","end":"1369195199"},

"2":{"id":"519d442a2b29c","title":"event 1","start":"1368504000","end":"1368590399"}}

I don't see why this is happening.

Upvotes: 0

Views: 136

Answers (1)

neouser99
neouser99

Reputation: 1827

Unset preserves indexes, creating the structure you are seeing. See this answer about using splice if you want to change the array, and re-index the items.

Upvotes: 1

Related Questions