我相信你做错了什么。看看这个:
$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 的索引。
如果您的情况不起作用,请尝试一下 - 这应该有效,并且应该让您知道自己做错了什么。