有效地从 PHP 数组中选取 n 个随机元素(无随机播放) [英] Efficiently pick n random elements from PHP array (without shuffle)

查看:25
本文介绍了有效地从 PHP 数组中选取 n 个随机元素(无随机播放)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码从 PHP 中的数组 $array 中选取 $n 元素:

I have the following code to pick $n elements from an array $array in PHP:

shuffle($array);
$result = array_splice($array, 0, $n);

给定一个大数组但只有几个元素(例如 10000 中的 5),这相对较慢,所以我想优化它,使其不所有元素都必须打乱.这些值必须是唯一的.

Given a large array but only a few elements (for example 5 out of 10000), this is relatively slow, so I would like to optimize it such that not all elements have to be shuffled. The values must be unique.

我正在寻找性能最高的替代方案.我们可以假设 $array 没有重复项并且是 0 索引.

I'm looking fo the most performant alternative. We can assume that $array has no duplicates and is 0-indexed.

推荐答案

$randomArray = [];
while (count($randomArray) < 5) {
  $randomKey = mt_rand(0, count($array)-1);
  $randomArray[$randomKey] = $array[$randomKey];
}

这将提供 5 个没有重复的元素并且非常快.密钥将被保留.

This will provide exactly 5 elements with no duplicates and very quickly. The keys will be preserved.

注意:您必须确保 $array 有 5 个或更多元素,或者添加某种检查以防止无限循环.

这篇关于有效地从 PHP 数组中选取 n 个随机元素(无随机播放)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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