Unsetting index in array turns it to an object

ぃ、小莉子 提交于 2019-12-04 04:02:28

问题


So I have a JSON document I'm storing in 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:

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?


回答1:


I fixed it like this:

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



回答2:


Instead of using unset, use array_splice. This will automatically adjust the array indexes:

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


来源:https://stackoverflow.com/questions/21346676/unsetting-index-in-array-turns-it-to-an-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!