1
\$\begingroup\$

Jst to clarify, teams and groups are the same thing in this case.

$data comes from a database and is an array of objects. Each object contains information about a user including what team/group they are in. I want to convert this to an array of groups which includes an array of users belonging to that group inside. Users can be in multiple groups too so in the original list of users, a lot of entries will have repeating group id's.

The code I have works but it's very blocky and I feel like it could be shortened a lot.

$groups = [];

foreach($data as $user)
{
    $userGroupId = $user['GroupId'];
    $exists = false;

    foreach($groups as &$group)
    {
        $groupId = $group['GroupId'];

        if ($groupId == $userGroupId)
        {
            $users = &$group['users'];

            $currentUser = array(
                'UserId'=>$user['UserId'],
                'UserName'=>$user['UserName'],
                'Surname'=>$user['Surname']
            );

            array_push($users, $currentUser);
            $exists = true;
            break;
        }
    }

    if (!$exists)
    {
        $addGroup = array(
            'GroupId'=>$user['GroupId'],
            'GroupName'=>$user['GroupName'],
            'users'=>[array(
                'UserId'=>$user['UserId'],
                'UserName'=>$user['UserName'],
                'Surname'=>$user['Surname']
              )]
        );

        array_push($groups, $addGroup);
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.