从 PHP 数组中获取随机值,但使其唯一 [英] get random value from a PHP array, but make it unique

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

问题描述

我想从数组中随机选择一个值,但尽可能保持它的唯一性.

I want to select a random value from a array, but keep it unique as long as possible.

例如,如果我从 4 个元素的数组中选择一个值 4 次,则选择的值应该是随机的,但每次都不同.

For example if I'm selecting a value 4 times from a array of 4 elements, the selected value should be random, but different every time.

如果我从 4 个元素的同一个数组中选择它 10 次,那么显然某些值会重复.

If I'm selecting it 10 times from the same array of 4 elements, then obviously some values will be duplicated.

我现在有这个,但我仍然得到重复的值,即使循环运行了 4 次:

I have this right now, but I still get duplicate values, even if the loop is running 4 times:

$arr = $arr_history = ('abc', 'def', 'xyz', 'qqq');

for($i = 1; $i < 5; $i++){
  if(empty($arr_history)) $arr_history = $arr; 
  $selected = $arr_history[array_rand($arr_history, 1)];  
  unset($arr_history[$selected]); 
  // do something with $selected here...
}

推荐答案

您几乎做对了.问题是 unset($arr_history[$selected]); 行.$selected 的值不是一个键,而是一个值,所以 unset 不起作用.

You almost have it right. The problem was the unset($arr_history[$selected]); line. The value of $selected isn't a key but in fact a value so the unset wouldn't work.

为了保持它与你在那里所拥有的一样:

To keep it the same as what you have up there:

<?php

$arr = $arr_history = array('abc', 'def', 'xyz', 'qqq');

for ( $i = 1; $i < 10; $i++ )
{
  // If the history array is empty, re-populate it.
  if ( empty($arr_history) )
    $arr_history = $arr;

  // Select a random key.
  $key = array_rand($arr_history, 1);

  // Save the record in $selected.
  $selected = $arr_history[$key];

  // Remove the key/pair from the array.
  unset($arr_history[$key]);

  // Echo the selected value.
  echo $selected . PHP_EOL;
}

或者一个少几行的例子:

Or an example with a few less lines:

<?php

$arr = $arr_history = array('abc', 'def', 'xyz', 'qqq');

for ( $i = 1; $i < 10; $i++ )
{
  // If the history array is empty, re-populate it.
  if ( empty($arr_history) )
    $arr_history = $arr;

  // Randomize the array.
  array_rand($arr_history);

  // Select the last value from the array.
  $selected = array_pop($arr_history);

  // Echo the selected value.
  echo $selected . PHP_EOL;
}

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

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