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

标签 php mysql laravel collections eloquent

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

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

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

谢谢你的帮助

最佳答案

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

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

关于php - 如何获取 Laravel 集合中元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53661967/

相关文章:

mysql - 我需要 Prestashop 产品的 mysql 查询(导入/导出)公式

javascript - 拉维尔 5.6 : intl-tel-input compatibility issue with App. js

laravel - Nwidart Laravel 模块使用 webpack 和 mix 管理资源。

不带引号的 PHP 数组键字符串

php - 使用 UPDATE 时,MySQL 将列设置为变量值的正确方法是什么?

php - MySQL 查询正在创建重复行

php - 从不同表插入时自动增量重叠

php - laravel 5.5 资源 restful API

php - Yoast 面包屑插件显示 1

laravel - 如何获取视频的持续时间 - laravel