如果主JSON对象(“ master”)中的对象,我试图将一个对象(“ new_item”)添加到数组中。如果新对象ID已存在于数组中,那么我先从数组中删除该对象,然后再添加它(因此,每个ID只有一个条目)。
出于某种原因,当我这样做时,对象数组将转换为我不想要的对象列表。
如果我仅删除重复项或允许重复项,则不会发生,仅当我删除一个元素然后添加另一个元素时,才会发生这种情况。
$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);
输出
{"master":{"0":{"id":"1","author":"A"},"2":{"id":"2","author":"B"}}}
反对
{"master":[{"id":"1","author":"A"},{"id":"2","author":"B"}]}
json_encode()
仅在索引从0
开始为连续的情况下才将数组编码为JSON数组。否则,它将被编码为对象。由于执行了unset($object->master[$key])
,因此在索引中创建了一个间隙,因此得到了一个对象,因为没有其他方法可以指示数组在索引1处没有任何内容。
您可以使用array_values()
重新编号索引,以消除间隔。
if ( count($object->master) == 0 ) {
$object->master = Array($new_item);
} else {
array_push($object->master, $new_item);
$object->master = array_values($object->master);
}