I have an array with weights on each value used to retrieve a random value based on those weights. I have used something like this in the past:
$items = array( "value1" => 30, "value2" => 70 );
$weighted = array();
foreach( $items as $value => $weight ) {
$weighted = array_merge($weighted, array_fill(0, $weight, $value));
}
echo $result = $weighted[array_rand($weighted)];
But what if I need to use decimals on the weights? (The weights I use always sum up to 100 btw)
For example:
$items = array( "value1" => 0.5, "value2" => 99.5 );
So value1 would only be shown 0.5% of the times.
Aucun commentaire:
Enregistrer un commentaire