Home >Backend Development >PHP Tutorial >Add weight factor to random sorting in PHP
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('a'=>10,'b'=>20,'c'=>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('a'=>10,'b'=>20,'c'=>50)); echo $row; ?>
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!