我正在从表中检索id的列表:
$users = User::all();
$ids_list = $users->lists('id')->all();
然后我正在做一些操作,从列表中删除某些ID:
unset($ids_list[$i]);
然后我试图将它存储在数据库中,但收到奇怪的结果:
有时它会像这样存储:[3,13]
,有时像这样:{"0":2,"2":27}
这是以这种方式行事的?
答案 0 :(得分:1)
我认为问题在于Laravel是json编码你传递的值。当json对数组进行编码时,如果键没有递增以0开头的数值,则json-encoding将其视为具有数字属性名称的对象。
由于您要移除值,因此递增链在某处中断。
尝试保存前,尝试通过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"]