I am trying to add an object ("new_item") to an array if objects in a master JSON object ("master"). If the new object ID already exists in the array I first remove that object from the array before then adding it again afterwards (so there is only one entry per ID).
For some reason when I do this the Array of objects gets converted to a list of objects which I don't want.
This doesn't happen if I only remove the duplicate or allow duplicates, it only seems to happen when I remove one element and then add another.
$object = '{"master":[{"id":"1","author":"A"},{"id":"2","author":"B"}]}';
$object = json_decode($object);
$new_item = '{"id":"2","author":"B"}';
$new_item = json_decode($new_item);
foreach ( $object->master as $key => $item ) {
if ( $item->id == $new_item->id ) {
unset($object->master[$key]);
}
}
if ( count($object->master) == 0 ) {
$object->master = Array($new_item);
} else {
array_push($object->master, $new_item);
}
echo json_encode($object);
Outputs
{"master":{"0":{"id":"1","author":"A"},"2":{"id":"2","author":"B"}}}
As oppose to
{"master":[{"id":"1","author":"A"},{"id":"2","author":"B"}]}