php中按权重数组中的随机值 [英] Random value from array by weight in php

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

问题描述

我知道可能有人问过这个问题,但我对之前的问题的理解不够充分,无法知道他们是否按照我的意愿行事.

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');

键是值被选中的机会的百分比.我想 mt_rand() 一个 0 到 99 之间的数字,并根据这些百分比从 $fruits 返回一个值.

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.

预先感谢您的帮助.

希望从 $fruits 中获得一个随机值,基于这些机会:

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

我想要 40% 的机会得到一个橙子,40% 的机会得到一个梨子,80% 的机会得到一个苹果.

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

为了进一步澄清,由于很多答案都弄错了(或者我只是不明白他们的代码),无论我选择什么数字,我都需要一个结果,而不仅仅是 20、40 或40.

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.

推荐答案

我认为这样的事情可以满足您的需求:

sample

(多次点击示例上的提交按钮,让代码重新执行)

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)];

这将创建一个数组 ($newFruits),它是一个具有 100 个元素的数字索引数组.其中 20 个元素是苹果",40 个是橙色",40 个是梨".然后我们从该数组中选择一个随机索引.100 次中有 20 次你会得到苹果",100 次中有 40 次你会得到橙色",100 次中有 40 次你会得到梨".

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天全站免登陆