如何从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];
}