如何获取laravel集合中元素的索引

btqmn9zl  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(390)

如何检索集合中元素的索引?我的代码:

$users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();

if($users->contains(Auth::id())){
    //get the index of auth user id
 }

谢谢你的帮助

doinxwow

doinxwow1#

$users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();

// this return a collection. So can do an if like this: $userIndex->count() > 0
$userIndex = $users->filter(function($user) {
    return $user->id === Auth::id()
});
nukf8bse

nukf8bse2#

你可以用这个收藏 search() 方法:https://laravel.com/docs/5.7/collections#method-搜索

$users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();

$userIndex = $users->search(function($user) {
    return $user->id === Auth::id();
});

小心点,因为索引可能是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
}

相关问题