更好的方式随机在PHP的数组中选择一个键值对 [英] A better way to randomly select a key and value pair from an array in PHP

查看:162
本文介绍了更好的方式随机在PHP的数组中选择一个键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知 array_rand()只能从这样的一个数组抢radnom数组:

As far as I know array_rand() can only grab a radnom array from an array like this:

$array = array( 'apple', 'orange', 'banana' );
$two_random_items = array_rand( $array , 2 ); // outputs i.e. orange and banana

但如何才能使我抓住2随机项目,但与键值数组?喜欢这个?

But how can I grab 2 random items but with the key value array? Like this?

$array = array( '0' => 'apple', '1' => 'orange', '2' => 'banana' );
$rand_keys = array_rand($array, 2);
$rand_values = array();
foreach ($rand_keys as $key) {
    $rand_values[] .= $array[$key];
}

这可能不是正确的方式,这是一个很多code的。

That's probably not the right way and it's a lot of code.

我有一个大数组这只是一个例子,我需要从父阵列随机抓取1000+以上的项目,并把它们放到一个新的数组,键可以复位,这并不重要。值的部分必须保持不变,当然。

I have a big array this is just an example and I need to grab 1000+ or more items randomly from the parent array and put them in a new array, keys can be reset, this is not important. The value part has to stay the same, of course.

有没有更好的办法如何实现这一目标?

Is there a better way how to achieve this?

推荐答案

只是洗牌和切片2:

shuffle($array);
$rand_values = array_slice($array, 0, 2);

这篇关于更好的方式随机在PHP的数组中选择一个键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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