Home > Backend Development > PHP Tutorial > Add weight factor to random sorting in PHP

Add weight factor to random sorting in PHP

*文
Release: 2023-03-18 11:46:01
Original
2117 people have browsed it

Many people know PHP random sorting, but how to implement weighted random sorting? This article will share the data randomly sorted according to weight, I hope it will be helpful to everyone.

The specific implementation method is as follows:

<?php   
/**  
 * @param array $weight 权重  例如array(&#39;a&#39;=>10,&#39;b&#39;=>20,&#39;c&#39;=>50)  
 * @return string key   键名   
 */  
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(&#39;a&#39;=>10,&#39;b&#39;=>20,&#39;c&#39;=>50));   
echo $row;   
?>
Copy after login


Related recommendations:

in PHP Three sorting methods for arrays php quick sort php sorting algorithm php sorting function

php sorting algorithm program does not require recursion

PHP common sorting algorithm learning


The above is the detailed content of Add weight factor to random sorting in PHP. For more information, please follow other related articles on the PHP Chinese website!

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