Answer the question
In order to leave comments, you need to log in
Random with probability for elements?
Hello, how can I make a function that will display a random result from an array? These elements have a drop chance.
[
{
"id" : 1,
"chance" : 10
},
{
"id" : 20,
"chance" : 70
},
{
"id" : 34,
"chance" : 20
}
]
Answer the question
In order to leave comments, you need to log in
Sea of solutions. Depends on your imagination.
I would do this:
1. Calculate the current drop chance, something like this mt_rand(0, 10000) / 100.
2. Filter the array to remove elements with a chance lower than step 1.
3. Run array_shuffle, for example.
4. Select the desired number of elements.
If the chance is needed for each element to count separately, then accordingly it happens during filtering. Fortunately, there is filtering with a callback: php.net/manual/ru/function.array-filter.php
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question