从PHP数组中获取随机值,但要使其唯一

Ale*_*lex 9 php arrays random

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

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

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

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

$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...
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*nes 11

你几乎把它做对了.问题是这unset($arr_history[$selected]);条线.值$selected不是键,但实际上是一个值,因此未设置不起作用.

为了使它与你在那里保持一致:

<?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;
}
Run Code Online (Sandbox Code Playgroud)

或者少一些行的示例:

<?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;
}
Run Code Online (Sandbox Code Playgroud)

  • @Alex - 不,实际上,当你没有指定键时,PHP会从0开始为它们分配数字键.请参阅[http://ca3.php.net/manual/en/function.array的参数部分. php](http://ca3.php.net/manual/en/function.array.php)了解更多信息. (2认同)

zzz*_*Bov 7

如何改变阵列,并弹出项目.

pop返回null,重置阵列.

$orig = array(..);
$temp = $orig;
shuffle( $temp );

function getNextValue()
{
  global $orig;
  global $temp;

  $val = array_pop( $temp );

  if (is_null($val))
  {
    $temp = $orig;
    shuffle( $temp );
    $val = getNextValue();
  }
  return $val;
}
Run Code Online (Sandbox Code Playgroud)

当然,你会想要更好地封装它,并做更好的检查,以及其他类似的事情.