简体   繁体   English

在数组中取消设置索引会将其转换为对象

[英]Unsetting index in array turns it to an object

So I have a JSON document I'm storing in CouchDB. 所以我有一个JSON文档,我将其存储在CouchDB中。 Here's the important part of it: 这是它的重要部分:

"games": {
   "creator": [
       "cf86d68b24c1bbf22702356572027642",
       "cf86d68b24c1bbf22702356572027dd8",
       "cf86d68b24c1bbf22702356572028b77"
   ],
   "solver": {
   }
}

I'm trying to remove one item from the array, let's say index 1: 我试图从数组中删除一个项目,让我们说索引1:

error_log("pre unset: " . json_encode($user->games));
unset($user->games->creator[1]);
error_log("post unset: " . json_encode($user->games));

The problem is, it keeps converting my array to an object, like so: 问题是,它不断将我的数组转换为一个对象,如下所示:

pre unset: {"creator":["cf86d68b24c1bbf22702356572027642","cf86d68b24c1bbf22702356572027dd8","cf86d68b24c1bbf22702356572028b77"],"solver":{}}
post unset: {"creator":{"0":"cf86d68b24c1bbf22702356572027642","2":"cf86d68b24c1bbf22702356572028b77"},"solver":{}}

What's going on, and how do I fix it? 发生了什么,我该如何解决?

I fixed it like this: 我这样修好了:

unset($user->games->creator[1]);
$user->games->creator = array_values($user->games->creator);

Instead of using unset , use array_splice . 而不是使用unset ,使用array_splice This will automatically adjust the array indexes: 这将自动调整数组索引:

array_splice($user->games->creator, 1, 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM