如何获取 Laravel 集合中元素的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53661967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:11:47 来源:igfitidea点击:
How to get index of element in Laravel collection
提问by user2916349
How to retrieve the index of an element in a collection ? My code :
如何检索集合中元素的索引?我的代码:
$users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();
if($users->contains(Auth::id())){
//get the index of auth user id
}
Thank's for help
感谢帮助
回答by newUserName02
You can use the collection search()
method: https://laravel.com/docs/5.7/collections#method-search
可以使用采集search()
方法:https: //laravel.com/docs/5.7/collections#method-search
$users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();
$userIndex = $users->search(function($user) {
return $user->id === Auth::id();
});
Just be careful, because the index might be 0:
请小心,因为索引可能为 0:
// DON'T do this
if($userIndex) {
// this will get skipped if the user is the first one in the collection
}
// Do this instead
if($userIndex !== false) {
// this will work
}