如何从PHP中的数组中选择随机值? [英] How do I select random values from an array in PHP?

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

问题描述

我在PHP中有一个对象数组.我需要随机选择8个.我最初的想法是使用array_rand(array_flip($my_array), 8),但这是行不通的,因为对象不能用作数组的键.

I have an array of objects in PHP. I need to select 8 of them at random. My initial thought was to use array_rand(array_flip($my_array), 8) but that doesn't work, because the objects can't act as keys for an array.

我知道我可以使用shuffle,但是随着数组大小的增加,我担心性能.那是最好的方法,还是有更有效的方法?

I know I could use shuffle, but I'm worried about performance as the array grows in size. Is that the best way, or is there a more efficient way?

推荐答案

$result = array();
foreach( array_rand($my_array, 8) as $k ) {
  $result[] = $my_array[$k];
}

这篇关于如何从PHP中的数组中选择随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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