代码之家  ›  专栏  ›  技术社区  ›  Simpledev

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

  •  0
  • Simpledev  · 技术社区  · 7 年前

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

    $users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();
    
    if($users->contains(Auth::id())){
        //get the index of auth user id
     }
    

    1 回复  |  直到 7 年前
        1
  •  18
  •   newUserName02    7 年前

    您可以使用集合 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();
    });
    

    // 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
    }
    
        2
  •  -2
  •   Franke Developer    5 年前
    $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()
    });