2

The title is pretty much self-explanatory so I will go straight to the problem.

Let's assume I have an array of some items like this:

$classicRoles = [
    'mafia', 
    'mafia', 
    'don', 
    'civilian', 
    'civilian', 
    'civilian', 
    'civilian', 
    'civilian', 
    'civilian', 
    'sherif'
];

Now after a query is executed I get the next array

while ($participantAssoc = mysqli_fetch_assoc($participantsQuery)) {
    $pushArray['room_id'] = $participantAssoc['room_id'];
    $pushArray['participant_id'] = $participantAssoc['participant_id'];
    $pushArray['id'] = $participantAssoc['id'];
    $pushArray['role'] = $participantAssoc['role'];
    $pushArray['eliminated'] = $participantAssoc['eliminated'];
    array_push($participantsArray, $pushArray);
}

Everything is fine here unless I try the next item.

I am trying to give each participant a role: 2 mafia roles, 1 don role, 6 civilians and 1 sheriff.

The issue is that the I can't get it working at all.

So the participants count can only vary for 1 item but let's even assume that the participants count and the roles' count are fully equal to each other. So for now, can anyone tell me how could I make the above mentioned logic happen within PHP arrays? (give each participant a role: 2 mafia roles, 1 don role, 6 civilians and 1 sheriff.)

Cave Johnson
  • 6,499
  • 5
  • 38
  • 57
Volo Apps
  • 235
  • 1
  • 3
  • 12

2 Answers2

1

This works if the participant count is less than or equal to the roles. Shuffle the array of roles to randomize it:

shuffle($classicRoles);

Then in the loop, remove one from the roles array and assign to your new array:

$pushArray['role'] = array_pop($classicRoles);

You haven't stipulated what should happen if you have more participants than roles, but something like:

if(count($classicRoles) > 0) {
    $pushArray['role'] = array_pop($classicRoles);
} else {
    break;
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • you are right i did not specify that case although clearly enough but as you can see in the array the roles are divided into the number of array count which is the max so it will not ever happen that the array of users would be more then the array of roles,let's assume we are playing yakudza with 20 players,so the role array will include 20 items – Volo Apps Mar 20 '17 at 20:55
  • i will use this code now and see how it works as the array_pop did not come into my mind though – Volo Apps Mar 20 '17 at 20:56
0

For each element of your roles array, pick a random user from your users array (array_rand()), and delete the given user key from the available users array.

That should do the trick.

foreach($classicRoles as $role) {
    $userKey = array_rand($participantAssoc);
    $currentUser = $participantAssoc[$userKey];
    $currentUser['role'] = $role;
    $participantsArray[] =  $currentUser;
    unset($participantAssoc[$userKey]);
}
Marc Brillault
  • 1,902
  • 4
  • 21
  • 41