重量在PHP从数组随机值 [英] Random value from array by weight in php

查看:116
本文介绍了重量在PHP从数组随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,这个问题可能已经被问过,但我不明白,不够了解,如果他们做我想做的。事先问题

  $水果=阵列('20'=>'苹果','40'=>'橙色','40'=>'梨');

键是越来越挑价值的机会的百分比。我想基于这些百分比来mt_rand()0到99之间的号码,从$返回一个值的果实。

这是非常有可能的我很困惑,因为我不知道该怎么解释我要找的。

感谢您预先的帮助。

编辑:想从$水果,一个随机值基于这些机会:

我要得到一个橘子有40%的机会,得到一个梨的40%的机会,并获得一个苹果80%的机会。

编辑:为了进一步澄清,因为不是很多答案听错了,(或者我只是不明白,他们的code),我需要一个结果,不管我选择什么样的数量,不只是20, 40,或40。


解决方案

我觉得这样的事情会做你想要什么:

样品

(点击样品上按钮多次提交,以获得$ ​​C $ C重新执行)

  $水果=阵列('苹果'=>'20','橙'=>'40','鸭梨'=>'40');$ newFruits =阵列();
的foreach($水果为$水果=> $值)
{
    $ newFruits = array_merge($ newFruits,array_fill(0,$价值$果));
}$ myFruit = $ newFruits [array_rand($ newFruits)];

这将创建一个数组( $ newFruits ),这是一个数字索引数组100的元素。这些元素中的20个是苹果,40是橙色,40是梨。然后,我们选择从数组随机指标。 20次满分100,你会得到苹果,40次满分100,你会得到'橙色',40倍出的100,你会得到'梨'。

I understand that this question has likely been asked, but I don't understand the prior questions enough to know if they do what I want.

$fruits = array('20' => 'apple', '40' => 'orange', '40' => 'pear');

The keys are percentages of the chance of value getting picked. I would like to mt_rand() a number between 0 and 99 and return a value from $fruits based on those percentages.

It's very possible I'm so confused because I don't know how to explain what I'm looking for.

Thank you in advance for the help.

Edit: want a random value from $fruits, based on these chances:

I want a 40% chance of getting an orange, a 40% chance of getting a pear, and an 80% chance of getting an apple.

Edit: To further clarify, since either a lot of the answers got it wrong, (or I just don't understand their code), I needed a result regardless of what number I pick, not just 20, 40, or 40.

解决方案

I think something like this will do what you want:

sample

(click the submit button multiple times on the sample to get the code to re-execute)

$fruits = array('apple' => '20', 'orange' => '40', 'pear' => '40');

$newFruits = array();
foreach ($fruits as $fruit=>$value)
{
    $newFruits = array_merge($newFruits, array_fill(0, $value, $fruit));
}

$myFruit = $newFruits[array_rand($newFruits)];

This creates an array ($newFruits), which is a numerically-indexed array with 100 elements. 20 of those elements are 'apple', 40 are 'orange', and 40 are 'pear'. Then we select a random index from that array. 20 times out of 100 you will get 'apple', 40 times out of 100 you will get 'orange', and 40 times out of 100 you will get 'pear'.

这篇关于重量在PHP从数组随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆