Search code examples
phparraysequalitydividearray-unset

Divide Array Items To Anothe Array Equally In Random Order Php


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


Solution

  • 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;
    }