我相信你做錯了什麼。看看這個:
$users = collect([
(object)['id' => 5, 'value' => 30, 'something' => 'else'],
(object)['id' => 6, 'value' => 40, 'something' => 'else2'],
(object)['id' => 7, 'value' => 50, 'something' => 'else3'],
(object)['id' => 8, 'value' => 60, 'something' => 'else4'],
(object)['id' => 9, 'value' => 70, 'something' => 'else5'],
(object)['id' => 30, 'value' => 90, 'something' => 'else6'],
]);
$users = $users->mapWithKeys(function($user, $key) {
return [$user->id => $user];
});
dd($users);
的這裏的結果是:
Collection {#374
#items: array:6 [
5 => {#364
+"id": 5
+"value": 30
+"something": "else"
}
6 => {#363
+"id": 6
+"value": 40
+"something": "else2"
}
7 => {#362
+"id": 7
+"value": 50
+"something": "else3"
}
8 => {#361
+"id": 8
+"value": 60
+"something": "else4"
}
9 => {#356
+"id": 9
+"value": 70
+"something": "else5"
}
30 => {#357
+"id": 30
+"value": 90
+"something": "else6"
}
]
}
完全按照預期。您確定不使用例如dd($users->values())
顯示結果嗎?因爲values()
將刪除這些密鑰,在這種情況下,您將獲得從0到5的索引。
您的情況不起作用,請嘗試使用此功能 - 這應該可以工作,並且應該讓您知道您做錯了什麼。