# php Simple Weight Calculation Method Example [Suitable for Lucky Draw Applications]

• 2021-12-12 03:56:06
• OfStack

In this paper, an example is given to describe the simple calculation method of weight in php. Share it for your reference, as follows:

``````
// Simple weight calculator
\$data222=array(
0=>array('id'=>1,'name'=>'1 Wait for a prize ','weight'=>'3'),
1=>array('id'=>2,'name'=>'2 Wait for a prize ','weight'=>'1'),
2=>array('id'=>3,'name'=>'3 Wait for a prize ','weight'=>'5'),
3=>array('id'=>3,'name'=>'3 Wait for a prize ','weight'=>'1'),
);
//  The higher the weight value, the greater the probability of being returned
//  Principle generates the array word of the number of weights, and enters array(5 A 0 , 10 A 1 , 25 A 2)
function countWeight(\$data){
\$i=0;
\$temp=array();
foreach(\$data as \$v){
for(\$i=0;\$i<\$v['weight'];\$i++){
\$temp[]=\$v;// Enlarge an array
}
}
\$num = count(\$temp);  // Check that there are errors on the Internet, and I have corrected them
\$int=mt_rand(0,\$num-1);// Get 1 Random number
\$result=\$temp[\$int];
return \$result;  // Return 1 Dimensional array
}
echo '<pre>';
var_dump(countWeight(\$data222));

``````

The effect after execution is

array(3) {
["id"]= >
int(2)
["name"]= >
string (9) "Second Prize"
["weight"]= >
string(2) "10"
}

PS: Here are two online tools with similar functions for your reference:

Online random number/string generation tool:
http://tools.ofstack.com/aideddesign/suijishu

Online random character/random password generation tool: