最近因项目需求需要做一个抽奖类的应用,用户点击抽奖,会返回三种不同的结果(即奖项:一等奖,二等奖,三等奖,谢谢抽奖),很显然,这个奖值出现的概率要依次降低了。这就涉及到了一个类似权重计算的一个算法了。根据需求想了很久,也总算是通过一个简单的权重计算办法将这件事情搞定了,概率还是在预计范围之内的。
下面就将这个权重计算的方法概述下。
首先说明的是这个例子在这里仅适合二维数组且一维为数字索引的数组,数据数组结构如下:
$data=array( 0=>array('id'=>1,'name'=>'一等奖','weight'=>'5'), 1=>array('id'=>2,'name'=>'二等奖','weight'=>'10'), 2=>array('id'=>3,'name'=>'三等奖','weight'=>'25'), 3=>array('id'=>4,'name'=>'谢谢抽奖','weight'=>'60') );
下面是简单计算权重的算法
// 权重数值越高,被返回的概率越大 // author www.Alixixi.com function countWeight($data){ $weight=0; $temp=array(); foreach($data as $v){ $weight+=$v['weight']; for($i=0;$i <p><font face="Courier New">计算结果返回如下:</font></p> <p><font face="Courier New">Array<br> (<br> [id] => 4<br> [name] => 谢谢抽奖<br> [weight] => 60<br> )</font></p> <p style="width:100%;text-align:center;margin:10px 0"> <br> <br> </p><p style="width:100%;text-align:center;margin:10px 0"> </p><p class="clear"></p>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article
Assassin's Creed Shadows: Seashell Riddle Solution
3 weeks agoByDDD
What's New in Windows 11 KB5054979 & How to Fix Update Issues
2 weeks agoByDDD
Where to find the Crane Control Keycard in Atomfall
3 weeks agoByDDD
Saving in R.E.P.O. Explained (And Save Files)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment