So let's take your original JSON as input
{
"array":[
"item",
"item2",
"item3"
]
}
You can use json_decode()
to convert the JSON data to PHP. Judging from your array modification code you want to provide true
as the second argument to json_decode()
$data = json_decode("{\"array\":[\"item\",\"item2\",\"item3\"]}", true);
You can then add data
$data['array'][] = array("x"=>"y","z"=>"a");
Now, you can use json_encode()
to convert the PHP data to JSON again
echo json_encode($data);
This will print
{
"array":[
"item",
"item2",
"item3",
{
"x":"y",
"z":"a"
}
]
}
You can alternatively pass JSON_FORCE_OBJECT
as the second argument to json_encode()
to force conversion of arrays to objects and thus the creation of keys
echo json_encode($data, JSON_FORCE_OBJECT);
This alternative call will print
{
"array":{
"0":"item",
"1":"item2",
"2":"item3",
"3":{
"x":"y",
"z":"a"
}
}
}
Note, that the call without JSON_FORCE_OBJECT
does not have the array indices, while your JSON data has them. The reason is in the different way you modify your data. You probably use the following code
$data['array']['newItem'] = array("x"=>"y","z"=>"a");
By providing a key for this new item it has to be represented as an object in JSON. The array now contains an object and all the other items are promoted to objects, too.
To fix your problem you should modify your data like so
$data['array'][] = array('newItem' => array("x"=>"y","z"=>"a"));
This will give you
{
"array":[
"item",
"item2",
"item3",
{
"newItem":{
"x":"y",
"z":"a"
}
}
]
}