Home > Backend Development > PHP Tutorial > PHP implements the method of randomly sorting data according to weight, PHP implements sorting_PHP tutorial

PHP implements the method of randomly sorting data according to weight, PHP implements sorting_PHP tutorial

WBOY
Release: 2016-07-13 10:09:53
Original
913 people have browsed it

php implements the method of randomly sorting data according to weight, php implements sorting

The example in this article describes the method of randomly sorting data according to weight in PHP. Share it with everyone for your reference.

The specific implementation method is as follows:

Copy code The code is as follows:

/**
* @param array $weight weight For example array('a'=>10,'b'=>20,'c'=>50)
* @return string key Key name
​*/
function roll($weight = array()) {
$roll = rand ( 1, array_sum ( $weight ) );
$_tmpW = 0;
$rollnum = 0;
foreach ( $weight as $k => $v ) {
$min = $_tmpW;
$_tmpW += $v;
$max = $_tmpW;
if ($roll > $min && $roll <= $max) {
$rollnum = $k;
Break;
}  

Return $rollnum;
}

$row=roll(array('a'=>10,'b'=>20,'c'=>50));
echo $row;
?>

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/940497.htmlTechArticlephp method to implement random sorting of data according to weight, php to implement sorting This article tells the example of php to implement random sorting of data according to weight method. Share it with everyone for your reference. Specific actual...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template