本文實例講述了php簡單計算權重的方法。分享給大家供大家參考,具體如下:
//簡單權重計算器$data222=array( 0=>array('id'=>1,'name'=>'一等獎','weight'=>'3'), 1=>array('id'=>2,'name'=>'二等獎','weight'=>'1'), 2=>array('id'=>3,'name'=>'三等獎','weight'=>'5'), 3=>array('id'=>3,'name'=>'三等獎','weight'=>'1'),);// 權重數值越高,被返回的概率越大// 原理生成權重個數的數組字,入array(5個0,10個1,25個2)function countWeight($data){ $i=0; $temp=array(); foreach($data as $v){ for($i=0;$i<$v['weight'];$i++){ $temp[]=$v;//放大數組 } } $num = count($temp); //查看網上的有錯誤,本人已改正 $int=mt_rand(0,$num-1);//獲取一個隨機數 $result=$temp[$int]; return $result; //返回一維數組}echo '<pre>';var_dump(countWeight($data222));
執行后的效果為
array(3) {
["id"]=>
int(2)
["name"]=>
string(9) "二等獎"
["weight"]=>
string(2) "10"
}
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選