简体   繁体   English

一种从PHP数组中随机选择键和值对的更好方法

[英]A better way to randomly select a key and value pair from an array in PHP

As far as I know array_rand() can only grab a radnom array from an array like this: 据我所知array_rand()只能从这样的数组中获取radnom数组:

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

But how can I grab 2 random items but with the key value array? 但是,如何使用键值数组来获取2个随机项呢? 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];
}

That's probably not the right way and it's a lot of code. 那可能不是正确的方法,而且代码很多。

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. 我有一个大数组,这只是一个例子,我需要从父数组中随机获取1000个或更多项,并将它们放入新数组中,可以重置键,这并不重要。 The value part has to stay the same, of course. 当然,价值部分必须保持不变。

Is there a better way how to achieve this? 有没有更好的方法来实现这一目标?

Just shuffle and slice 2: 只是随机播放并切片2:

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

First, this line: $rand_values[] .= $array[$key]; 首先,这一行: $rand_values[] .= $array[$key]; is wrong. 是错的。 The .= operator is to join strings, to add a value to the end of the array, you just need $rand_values[] = $array[$key]; .=运算符用于连接字符串,将值添加到数组的末尾,您只需要$rand_values[] = $array[$key]; .

If you don't care about the keys, just use array_values function to "dump" the keys. 如果您不关心键,只需使用array_values函数“转储”键即可。

$array = array('a' => 'orange', 'c' => 'banana', 'b' => 'peach');
$two_random_items = array_rand(array_values($array) , 2 );

array_values will strip down the keys, and will return an array with the values (the keys will become 0, 1, 2...) array_values将剥离键,并返回带有值的数组(键将变为0、1、2 ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM