dsiv4041 2012-11-19 21:31
浏览 42
已采纳

too long

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)

  • 写回答

1条回答 默认 最新

  • duanji7881 2012-11-19 21:39
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?