Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 692
snollygolly Avatar asked Jan 17 '26 18:01

snollygolly


1 Answers

I fixed it like this:

unset($user->games->creator[1]);
$user->games->creator = array_values($user->games->creator);
like image 170
snollygolly Avatar answered Jan 19 '26 07:01

snollygolly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!