Divide Array Items To Anothe Array Equally In Random Order Php

93 Views Asked by At

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.)

2

There are 2 best solutions below

2
AbraCadaver On BEST ANSWER

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;
}
0
Orange Lux On

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]);
}