Advertisement
  1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Split player array to each team in minigame right

Comments in 'Resources' started by MyNameIsTriXz, Oct 4, 2016.

  1. MyNameIsTriXz
    Offline

    MyNameIsTriXz Notable Member

    Joined:
    Aug 17, 2015
    Posts:
    538
    Minecraft User:
    MyNameIsTriXz
    I have recently seen a lot of minigame developers using array_chunk(); to split a player array to a team array, this function is good if the array index count can be divided through the team count (4 : 2, 6 : 3, 8 : 4, But not 6 : 4 or 4 : 3). But if you have as example 3 players and want to split them into 2 teams, then array_chunk will return useless results (in this case player3 will just be unset from the array)... But there is a custom function which I found on Stackoverflow, it's the fixed array _chunk():
    PHP:
    public function partition(Array $list$p) {
        
    $listlen count($list);
        
    $partlen floor($listlen $p);
        
    $partrem $listlen $p;
        
    $partition = array();
        
    $mark 0;
        for(
    $px 0$px $p$px ++) {
            
    $incr = ($px $partrem) ? $partlen $partlen;
            
    $partition[$px] = array_slice($list$mark$incr);
            
    $mark += $incr;
        }
        return 
    $partition;
    }
    Usage:

    Code:
    $this->partition(Array $playerarray, String $teams);
    
    

    Example:

    PHP:

    $array 
    = ["player1""player2""player3""player4""player5"];

    $this->partition($array4);
    // 5 players into 4 teams

    Will return:

    Code:
    array (size=4)
    0 =>
    array (size=2)
    0 => string 'p1' (length=2)
    1 => string 'p2' (length=2)
    1 =>
    array (size=1)
    0 => string 'p3' (length=2)
    2 =>
    array (size=1)
    0 => string 'p4' (length=2)
    3 =>
    array (size=1)
    0 => string 'p5' (length=2)
    
    

    Credits: http://stackoverflow.com/questions/15723059/split-array-into-a-specific-number-of-chuncks
    Last edited: Oct 4, 2016

Share This Page

Advertisement