我從檢索表ID的列表:Laravel怪陣/對象存儲問題
$users = User::all();
$ids_list = $users->lists('id')->all();
然後我做了一些操作,從列表中刪除某些IDS:
unset($ids_list[$i]);
然後我試圖將它存儲在數據庫中,但收到奇怪的結果: 有時它像這樣存儲:,有時是這樣的:{"0":2,"2":27}
這是怎麼回事?
我從檢索表ID的列表:Laravel怪陣/對象存儲問題
$users = User::all();
$ids_list = $users->lists('id')->all();
然後我做了一些操作,從列表中刪除某些IDS:
unset($ids_list[$i]);
然後我試圖將它存儲在數據庫中,但收到奇怪的結果: 有時它像這樣存儲:,有時是這樣的:{"0":2,"2":27}
這是怎麼回事?
我想問題是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"]
這是一個很好的答案!謝謝,它工作! –
我可以接受它前7分鐘... –
我添加了一些更多的細節來幫助說明PHP在內部做什麼,供您和其他人蔘考。希望這會有所幫助。這將有助於殺死7分鐘= P – stratedge
它,你是如何將未固化的不是很清楚。您所做的查詢是一個OBJECTS數組。這意味着$ ids_list [$ i] - > id將返回您請求的字段。你可以將查詢轉換爲這樣的數組:$ ids_list = $ users-> lists('id') - > all() - > toArray(); – Heroselohim