A simple method for calculating weights in PHP (suitable for lottery applications)

Source: Internet
Author: User
Tags array arrays return

Recently, as a result of the project needs to do a lottery application, users click the lottery, will return three different results (that is, awards: First prize, Second prize, third prize, thank you Lottery), it is clear that the probability of the prize value will be reduced in turn. This involves a similar calculation of the weight of an algorithm. According to the need to think for a long time, and finally through a simple weight calculation method to get this thing done, the probability is within the expected range.

Here is a summary of how this weight is calculated.

The first explanation is that this example is only suitable for arrays with two-dimensional arrays and one dimension is a numeric index, and the data array structure is as follows:

$data =array (
	0=>array (' id ' =>1, ' name ' => ' first prize ', ' Weight ' => ' 5 '),
	1=>array (' id ' =>2, ' name ' = > ' Second Prize ', ' Weight ' => '),
	2=>array (' id ' =>3, ' name ' => ' third prize ', ' Weight ' => '),
	3=>array ( ' id ' =>4, ' name ' => ' Thank you draw ', ' weight ' => ')
;

Here is a simple algorithm for calculating weights

The higher the weight value, the greater the probability of being returned
//author www.Alixixi.com
function countweight ($data) {
	$weight =0;
	$temp =array ();
	foreach ($data as $v) {
		$weight + = $v [' weight '];
		For ($i =0 $i < $v [' weight ']; $i + +) {
			$temp []= $v;//magnify Array
		}
	}
	$int =mt_rand (0, $weight-1);// Gets a random number
	$result = $temp [$int];
	return $result;
}

The calculated results are returned as follows:

Array
(
[ID] => 4
[Name] => Thank you for the lottery
[Weight] => 60
)



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.