开发者

random shuffle in php?

开发者 https://www.devze.com 2023-03-31 12:28 出处:网络
I\'m creating a lottery to pair up people. So I want a way to shuffle the strings in an array where no item ends up on the same place. (You can\'t pair up with yoursel开发者_开发百科f)

I'm creating a lottery to pair up people. So I want a way to shuffle the strings in an array where no item ends up on the same place. (You can't pair up with yoursel开发者_开发百科f)

    public function shuffleSantas(){
    $query = $this->db->get('person');
    $givers = array();
    $recievers = array();
    foreach($query->result() as $row):          
        $givers[] = $row->name;
        //here i want a random order, but no name can be on the same place as in $givers!
        $recievers[] = '';
    endforeach;


shuffle the array once and then pair up the first element with the second, the second with the third etc. and the last with the first.


$src = $query->result();
$givers = array();
$receivers = array();
foreach ($src as $idx=>$first_person){
    $count = 0; //infinite loop guard
    do{
        ++$count;
        $sec_idx = rand(0,count($src)-1);
        $second_person = $src[$sec_idx];
    } while ($second_person==$first_person && $count<5); 
    $givers[] = $first_person;
    $receivers[] = $second_person; 
}

In this case one will be able to receive from one person and to give to other person. Is it OK? Also, this algorithm is not optimal and will definitely fall into infinity loop if there is only one person in an array.


If think there is no built-in function in PHP to shuffle that way. You have to write your own function.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号