0

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.

2
  • 0 and 2 are the indexes and you deleted 1 Commented May 22, 2013 at 22:34
  • Its changing the JSON Array of Dictionaries to a JSON Dictionary of key:value pairs where keys are string version of i, I don't want that to happen. Commented May 22, 2013 at 22:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, using $array = $array_values($array); fixes it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.