-2

I have this array code

$data = array();
foreach($getAllUserTicketHistoryJson as $value){
    $data[$value['user_id']] = number_format((float)($value['total_ticket'] / $getAllTicketRound * 100), 2, '.', '');
}
$array=$data;

which will give output

array(4) { [4]=> string(5) "16.28" [3]=> string(4) "5.81" [2]=> string(5) "11.63" [5]=> string(5) "66.28" } 

the array is user_id and chance to win from 100%.

and I want to show 3 random winner without repeat the first winner. Means that if user already win they cannot win again.

I created this code

    $number=rand(0,array_sum($array));
    $starter=0;
    foreach($array as $key => $val)
    {
        $starter+=$val;
        if($number<=$starter)
        {
                $ret=$key;
                break;
        }
    }
for($i=0;$i<3;$i++)
{
    echo 'Winner is '.$ret.'<br/>';
}

The code will give output

Winner is 5
Winner is 5
Winner is 5

The problem is, how to show 3 winner based on their chance without repeating the first winner. The result should be like this

Winner is 4
Winner is 5
Winner is 2

thanks for helping me

1 Answers1

0

You need something like this, You can test it here: http://sandbox.onlinephpfunctions.com/code/0660c7223d301341cbb452314d18945b546e51c5

It will pass your array as reference to a function, so when the winner is selected, it is also removed from your array so there's no way it can be selected again.

// TEST DATA
$array = [
    4 => '16.28',
    3 => '5.81',
    2 => '11.63',
    5 => '66.28',
];

// GET WINNER
// pass the array by reference, so the winner can be removed (unset) from it
function getWinner(&$array) {
    $number=rand(0,array_sum($array));
    $starter=0;
    foreach($array as $key => $val)
    {
        $starter+=$val;
        if($number<=$starter)
        {
            unset($array[$key]);
            return $key;
        }
    }
}
// GET 3 WINNERS
for($i=0;$i<3;$i++)
{
    echo 'Winner is '.getWinner($array)."\n";
}
Balázs Varga
  • 1,797
  • 2
  • 16
  • 32