shreyash singh shreyash singh - 7 months ago 42
JSON Question

PHP - JSON Parsing - add and remove object

I am getting

This JSON string from server , I want to append another object ie.
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
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
giving output in object form like
While what is wanted is


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.