0

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?

1
  • It's not very clear how you are applying the unset. The query you have done it's an array of OBJECTS. This means that $ids_list[$i]->id will return your requested field. You can convert queries to arrays like this: $ids_list = $users->lists('id')->all()->toArray(); Commented Mar 11, 2016 at 19:52

1 Answer 1

1

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

I'm adding a little more detail to help illustrate what PHP is doing internally, for your and others' reference. Hopefully it'll be helpful. That'll help kill the 7 minutes =P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.