防止Foreach数组赋予相同的值

时间:2019-01-07 14:50:30

标签: php arrays

我有这个数组代码

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

这将提供输出

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

该数组是user_id,有机会从100%获胜。

,我想显示3个随机赢家,而无需重复第一个赢家。意味着如果用户已经获胜,他们将无法再次获胜。

我创建了这段代码

    $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/>';
}

代码将输出

Winner is 5
Winner is 5
Winner is 5

问题是,如何根据机会显示3个获胜者而不重复第一个获胜者。结果应该是这样

Winner is 4
Winner is 5
Winner is 2

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您需要类似的内容,可以在这里进行测试:http://sandbox.onlinephpfunctions.com/code/0660c7223d301341cbb452314d18945b546e51c5

它将把您的数组作为对函数的引用,因此当选择获胜者时,它也会从数组中删除,因此无法再次选择它。

// 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";
}