PHP:比array_rand()更好[Q&安培; A] [英] PHP: Better than array_rand() [Q&A]

查看:229
本文介绍了PHP:比array_rand()更好[Q&安培; A]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有次,其中 array_rand()是不够的。

虽然我知道它返回键,而不是值,我发现它的名称尚不清楚。

Although I know that it returns keys and not values, I find its name unclear.

但最重要的是, array_rand()不给予同等的机会,所有的按键(如 Array_rand不洗牌或的 Array_rand不是随机以及很多其他的例子)。

But most importantly, array_rand() does not give equal chances to all keys (as seen in Array_rand does not shuffle or Array_rand not random and plenty of other examples).

,以更好地随机数组中的一个显着的方式是函数洗牌(),但它可以是相当ressources苛刻,再加上如果该键是重要的,以及他们与丢失吧。

A notable way to better randomize the array is the function shuffle() but it can be quite ressources demanding, plus if the keys are important, well they are lost with it.

这将是一个很好的和更快的替代是略显笨拙的功能?

What would be a good and faster alternative to that slightly clumsy function?

推荐答案

我想出了这两个功能:

function random_key($array){
    $keys=array_keys($array);
    return $keys[mt_rand(0, count($keys) - 1)];
}

function random_value($array){
    $values=array_values($array);
    return $values[mt_rand(0, count($values) - 1)];
}

他们都与任何一种阵列工作良好,不改变原来的,是给更现实的随机的结果,他们的名字是自描述的。

They both work well with any kind of arrays, do not alter the original one, are giving more realistic random results, and their names are self describing.

的主要缺点是,相对于array_rand,它们可以只给一个元素

The main drawback is that as opposed to array_rand, they can only gives one element.

(帮着回答来自如何获得随机值出数组的)

这篇关于PHP:比array_rand()更好[Q&安培; A]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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