shreyash singh shreyash singh - 1 year ago 116
JSON Question

PHP - JSON Parsing - add and remove object

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"}]

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download