从一个数组PHP获取随机值的一个子集 [英] Get a subset of random values from an array php

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

问题描述

与10K值的数组开始。我想从它随机得到1000个值并把它们放到另一个数组。

Starting with an array with 10K values. I want to randomly get 1000 values from it and put them into another array.

现在,我使用的是循环得到的值,但我要挑1000个值,而不必循环1000次。所述array_slice功能的工作原理,但它不给随机值。什么是此任务的正确的(最有效)的功能。

Right now, I am using a for loop to get the values, but I want to pick 1000 values and not have to loop 1000 times. The array_slice function works, but it doesn't give random values. What is the correct (most efficient) function for this task.

在code现在是

$seedkeys = (...array.....);

for ($i=0; $i<1000; $i++) {
        $random = array_rand($seedkeys);  
    $randseed[$i] = $seedkeys[$random];   

}//for close

TIA

推荐答案

好了,有几个选择。我不知道这是最快的,因为你正在处理一个相当大的数组,但你可能想尝试一下:

Well, there are a few alternatives. I'm not sure which is the fastest since you're dealing with a sizable array, but you may want to try them out:

您可以使用 随机 ,这将随机整个数组。这可能将有最佳的性能,因为你消耗阵列(10%)的显著部分。

You can use shuffle, which will randomize the entire array. This will likely have the best performance since you're consuming a significant portion of the array (10%).

suffle($seedkeys);
$result = array_slice($seedkeys, 0, 1000);

您可以使用 array_rand (因为你已经说的)在汤姆·黑格指定庄园。这将需要复制的钥匙,所以如果你正在处理的源数组的显著部分,这可能不是最快的。 (注意使用 array_flip 的,它需要允许的使用 array_intersect_key

You could use array_rand (as you already said) in the manor that Tom Haigh specifies. This will require copying the keys, so if you're dealing with a significant portion of the source array, this may not be the fastest. (Note the use of array_flip, it's needed to allow the usage of array_intersect_key:

$keys = array_flip(array_rand($seedkeys, 1000));
$result = array_intersect_key($seedkeys, $keys);

如果存储器是紧,最好的解决方案(除了MySQL的一个)将是一个循环,因为它不要求阵列在所有被复制。请注意,这会慢一些,但是如果数组包含了大量的信息,它可能会通过更高效的内存(因为它只会复制正是它返回)...

If memory is tight, the best solution (besides the MySQL one) would be a loop since it doesn't require arrays to be copied at all. Note that this will be slower, but if the array contains a lot of information, it may offset the slowness by being more memory efficient (since it only ever copies exactly what it returns)...

$result = array();
for ($i = 0; $i < 1000; $i++) {
    $result[] = $seedkeys[array_rand($seedkeys)];
}

您可以做到这一点在MySQL中(假设为阵列中的数据从MySQL开始)。要知道,这是简单的,但不是有效的(见月Kneschke的帖子)...

You could do it in MySQL (assuming that the data for the array starts from MySQL). Be aware this is simple, but not that efficient (See Jan Kneschke's post)...

SELECT * FROM `foo` ORDER BY RAND() LIMIT 1000;

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

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