Jess J
Jess J

Reputation: 83

Laravel strange array/object storing issue

I'm retrieving list of id's from the table:

$users = User::all();
$ids_list = $users->lists('id')->all();

Then I'm doing some manipulations, removing certain ids from the list:

unset($ids_list[$i]);

Then I'm trying to store it in the database, but receive strange results: Sometimes it stores like this: [3,13], and sometimes like this:{"0":2,"2":27}

Whys is it acting this way?

Upvotes: 0

Views: 204

Answers (1)

stratedge
stratedge

Reputation: 2820

I think the problem is that Laravel is json-encoding the values you are passing. When you json encode an array, if the keys are not incrementing numerical values starting with 0, then the json-encoding treats it like an object with numeric property names.

Since you are removing values, the incrementing chain is broken in the middle somewhere.

Try running your final array through array_values() before trying to save. Array values will re-index your array so there are no gaps in the numbering.

Here's the documentation for array_values: http://php.net/manual/en/function.array-values.php


Edit 1 (extra explanation)

//Define our array
$arr = ['why', 'hello', 'there'];

//Array looks like this:
//Array (
//    [0] => 'why',
//    [1] => 'hello',
//    [2] => 'there'
//)

json_encode($arr); //Results in: ["why","hello","there"]

//Break the auto-incrementing numerical keys by removing a middle value
unset($arr[1]);

//Array now looks like this:
//Array (
//    [0] => 'why',
//    [2] => 'there'
//)

json_encode($arr); //Results in {"0":"why","2":"there"}

//The json is now an object because an array in javascript can't have a break
//in the numerical chain of its keys. Only an object can represent in javascript
//what our array looks like now

//In order to return the array to an unbroken chain of auto-incrementing
//numerical keys, we ask PHP just to give us the values of the array
$arr = array_values($arr);

//Array now looks like this:
//Array (
//    [0] => 'why',
//    [1] => 'there'
//)

json_encode($arr); //Results in ["why","there"]

Upvotes: 1

Related Questions