【问题标题】:Laravel, how to group a collection by a countLaravel,如何按计数对集合进行分组
【发布时间】:2017-05-22 06:51:43
【问题描述】:

如何使用数字对集合进行分组。所以我创建了一个接受数字的方法,然后使用该数字对返回的集合进行分组,因此如果我传入 4,它将按 4 分组。下面是数据的原始结构。

{
    'A': [{
        id: 1, 
        id: 2,
        id: 3,
        id: 4,
        id: 5,
        id: 6,
        id: 7
    }],
    'B': [{
        id: 1,
        id: 2,
        id: 3
    }],
    'C': [{
        id: 1,
        id: 2,
        id: 3,
        id: 4
    }]
}

现在我希望它以这种方式格式化数据。

{
    'A': [{
        1: [{
            id: 1, 
            id: 2,
            id: 3,
            id: 4
        }],
        2: [{
            id: 5,
            id: 6,
            id: 7
        }]
    }],
    'B': [{
        1: {
            id: 1,
            id: 2,
            id: 3
        }
    }],
    'C': [{
        1: [{
            id: 1,
            id: 2,
            id: 3,
            id: 4
        }]
    }]
}

这是我的代码。

public function getAllPlayers( num )
{
    $data = Player::orderBy('familyName', 'asc')
        ->join('teams', 'players.primaryClubId', '=', 'teams.clubId')
        ->select(['players.*', 'teams.teamName', 'teams.teamNickname', 'teams.teamCode'])
        ->get()
        ->unique() //remove duplicates
        ->groupBy(function($item, $key) { //group familyName that starts in same letter
            return substr($item['familyName'], 0, 1);
        });

    return $data;
}

我真的很难在 laravel 中解决这个问题。顺便说一句,我使用 5.4 版本。任何帮助将不胜感激,在此先感谢!

【问题讨论】:

  • 当前输入和结果结构不清楚。首先,它看起来像数组中的 JSON 结构,值 id 将被最后一个覆盖。请提供具有不同值的更好样本,以便解决问题。

标签: php laravel laravel-5 eloquent backend


【解决方案1】:

尝试使用map 函数,如下所示:

$data = Player::orderBy('familyName', 'asc')
    ->join('teams', 'players.primaryClubId', '=', 'teams.clubId')
    ->select(['players.*', 'teams.teamName', 'teams.teamNickname', 'teams.teamCode'])
    ->get()
    ->unique()
    ->groupBy(function($item, $key) {
        return substr($item['familyName'], 0, 1);
    })
    ->map(function ($subCollection) {
        return $subCollection->chunk(4); // put your group size
    });

【讨论】:

    猜你喜欢
    • 2018-08-20
    • 1970-01-01
    • 2022-10-14
    • 2014-06-07
    • 2017-10-04
    • 2021-04-18
    • 2017-11-20
    • 2021-07-16
    • 1970-01-01
    相关资源
    最近更新 更多