doutuobao9736 2016-10-12 15:46
浏览 114
已采纳

PHP - JSON解析 - 添加和删除对象

I am getting [{"2016":"200"},{"2017":"200"}] This JSON string from server , I want to append another object ie. {"2018":"324"} at the end of the existing JSON array and want to delete object at the 0th index the existing JSON array so that the my desired result [{"2017":"200"}{"2018":"324"}] can be obtained. Here's what i am doing

        $str = json_decode($x1,TRUE);                    //x1 is my JSON
        array_push($str, array("2018"=>"324"));     //adding another object
        unset($str[0]);                             //removing 0th index
        $s = json_encode($str,TRUE);                    //making JSON again
        echo $s;                

Problem here is $s giving output in object form like {"1":{"2017":"200"},"2":{"2018":"35"}} While what is wanted is [{"2017":"200"}{"2018":"324"}]

  • 写回答

1条回答 默认 最新

  • dqypcghd381390 2016-10-12 15:58
    关注

    I might suggest better approach, using array_shift():

    $json = json_decode($x1, TRUE);   // decoding
    
    array_shift($json);               // removing first element
    
    $json[] = [ "2018" => "324" ];    // adding last element
    
    $str = json_encode($json);        // encoding
    
    echo $str; 
    

    As others already pointed out, you getting object equivalent because your array not starting from 0 index, so it is converted in javascript object with numeric keys. I'm using array_shift() to remove first element. It will also reset indices in array. It also would be (insignificantly) faster, if you remove first key before adding other elements to array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?