带权重的随机算法

function roll($arr){

    //获取数组中所有值的和
    $count = array_sum($arr);
    $rand = 0;

    foreach($arr as $k => $v){
        $rand = mt_rand(1, $count);
        if( $rand <= $v){
            return $k;
        }
        else{
            $rand -= $v;
        }
    }
}

$array = ['a' => 5, 'b' => 3, 'c' => 1];
echo roll($array);

洗牌算法


function poker($array){
    $count = count($array);

    for($i=0; $i<$count; $i++){
      $rand = rand(200, 300);
      $index = $rand % $count;
      $tmp = $array[$i];
      $array[$i] = $array[$index];
      $array[$index] = $tmp;
    }
    return $array;
}

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g');
print_r( poker($array) );