1

I'm trying to search for an id in my json file and and remove that object with php.

In detail: I post the id with jQuery post to my delete.php and in my delete.php file I search for the id and unset it. But for some reason if I unset the first object it adds a number to my json and breaks it (I can still add more objects but breaks the first one).

// delete.php file looks like this:

if(isset($_POST['deleteData'])){
    $data = $_POST['deleteData'];
    $dataJSON = json_decode(file_get_contents('datas.json'), true);  
    for($i = 0, $dataJSONLength = count($dataJSON); $i < $dataJSONLength; $i++){
      if($dataJSON[$i][data][0][id] == $data){
        unset($dataJSON[$i]);
        echo 'deleted';// needed for callback for feedback
      }
    }
    file_put_contents('datas.json', json_encode($dataJSON));
  }

   

// add.php is:

if(isset($_POST['addData'])){
  $dataJSON = json_decode(file_get_contents('datas.json'), true);
  $dataJSON[] = $_POST['addData'];
  file_put_contents('datas.json', json_encode($dataJSON));
}

My datas.json file is fairly nested so I'll just post where the issue is:

[{"user":[{"browser":[{" // this is what it looks like when I add

{"1":{"user":[{"browser":[{" // this is what happens when I delete the first object. Notice "1" 

If I don't delete the first object everything works fine until the first object is deleted. Any suggestions? Thanks. (if needed I can post the whole json file)

ialphan
  • 1,241
  • 1
  • 17
  • 30
  • You might try moving all the items into a new array as you search: `if($dataJSON[$i][data][0][id] != $data) $newData[]=$dataJSON[$i];` – Jon Hulka Nov 19 '12 at 21:34

1 Answers1

1

PHP is turning your array into an object probably because unset is giving you an associative array rather than in indexed array. You should call array_splice instead of unset or else call array_values after unsetting your value per the ideas found in this post.

// your for loop:
for (...) {
    unset($dataJSON[$i]);
    ...
}
// After your for loop with all necessary values removed then call array_values to normalize the array.
$dataJSON = array_values($dataJSON);
Community
  • 1
  • 1
davidethell
  • 11,708
  • 6
  • 43
  • 63