The solution proposed by @bfavaretto in the comments works perfectly. Here’s another suggestion if you couldn’t solve it.
I made a solution based on a range of numbers that each element can have. The higher the chance percentage, the greater the range of numbers of each element. Based on your example, I created the following array:
$items = array(
"Item 1" => 0.5, // porcentagens
"Item 2" => 1,
"Item 3" => 4,
"Item 4" => 4.5,
"Item 5" => 5,
"Item 6" => 15,
"Item 7" => 15,
"Item 8" => 15,
"Item 9" => 20,
"Item 10" => 20
);
With this, a new array is generated with the name of each element and its respective ranges through this code:
$valor = 1000; // valor do peso máximo e total dos itens
$inicio = 1;
$ultimo_valor = 0;
$array_elementos = array(); // array para sorteio
// cria o array para sorteio
foreach($items as $nome => $porcentagem){
$val = ($valor * $porcentagem) / 100;
$valorFinal = $val + $inicio - 1;
$array_elementos[$nome] = $inicio."-".$valorFinal;
$inicio = $valorFinal + 1;
}
See how the array looks $array_elementos
:
Array (
[Item 1] => 1-5
[Item 2] => 6-15
[Item 3] => 16-55
[Item 4] => 56-100
[Item 5] => 101-150
[Item 6] => 151-300
[Item 7] => 301-450
[Item 8] => 451-600
[Item 9] => 601-800
[Item 10] => 801-1000
)
Now just draw a random number and search the array in which element the number is in. So:
// numero randômico "sorteio"
// de 1 até o valor máximo
$num_rand = rand(1, $valor);
$elemento_sorteado = "";
// procura o elemento sorteado
foreach($array_elementos as $nome => $peso){
$valores = explode("-", $peso);
if($num_rand >= $valores[0] && $num_rand <= $valores[1]){
$elemento_sorteado = $nome;
break;
}
}
echo $elemento_sorteado;
See the code working on ideone
A very simple way to make it work with the code you already have is popular the "box" according to percentages. For example, if 20% of the items in your box are copies of the value
10
, an index draw witharray_rand
will match with the item10
approximately 20% of the time.– bfavaretto
@bfavaretto did not understand very well, it would assign numbers according to the percentage of the item?
– Everton Neri
It would repeat the item within the array so that it has a higher chance of being drawn.
– bfavaretto
Everton, did you manage to test my code? Do you have any comments? Hug.
– Andrei Coelho