拉拉维尔奇怪的数组/对象存储问题


Laravel strange array/object storing issue

我正在从表中检索id列表:

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

然后我正在做一些操作,从列表中删除某些 id:

unset($ids_list[$i]);

然后我尝试将其存储在数据库中,但收到奇怪的结果:有时它存储如下:[3,13],有时存储如下:{"0":2,"2":27}

为什么会这样行事?

我认为

问题是Laravel正在对你传递的值进行json编码。对数组进行 json 编码时,如果键不是从 0 开始递增数值,则 json 编码会将其视为具有数字属性名称的对象。

由于您正在删除值,因此递增链在中间某处断开。

在尝试保存之前,请尝试通过array_values()运行最终阵列。数组值将重新索引数组,因此编号中没有间隙。

以下是array_values的文档:http://php.net/manual/en/function.array-values.php


编辑 1(额外说明)

//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"]