【问题标题】:Get five unique random PHP values selected from an array and put them in separate variables从数组中选择五个唯一的随机 PHP 值并将它们放入单独的变量中
【发布时间】:2018-06-07 14:06:42
【问题描述】:

我有一个数组,例如:

 array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");

我想从中选择五个随机且唯一的值,并将它们放入五个不同的变量中,例如:

    $one = "ccc"; 
    $two = "aaa";
    $three = "bbb"; 
    $four = "ggg";
    $five = "ddd";

我已经在下面找到了这段代码,它可用于生成随机字符串并仅显示它们,但我想要的输出是将它们放入不同的变量中并能够单独使用它们。

<?php

$arr = $arr_history = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");

for ( $i = 1; $i < 5; $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;
 }

【问题讨论】:

  • 它们必须是单独的变量还是可以是包含这五个具有数字索引的随机值的数组?
  • 顺便说一句,由于您的循环逻辑$i = 1; $i &lt; 5; $i++,您的循环不会显示五个项目@您需要使其成为&lt;=
  • @Script47 我认为它也可以与索引一起使用。我只需要能够在代码的不同部分使用它们。

标签: php arrays string random


【解决方案1】:

您可以shuffle 数组并使用list 分配值

$arr = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");

shuffle( $arr );
list($one, $two, $three, $four, $five) = $arr;

文档:shuffle()list()

【讨论】:

  • 感谢 Script47。很高兴帮助@ClaudioDelgado :)
【解决方案2】:

使用这个:

$arr = $arr_history = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
$random = [];

for ( $i = 1; $i <= 5; $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);

  array_push($random, $selected);
}

var_dump($random);
  • 我已修复您的循环逻辑,现在它显示 5 个项目而不是 4 个。
  • 我正在使用short syntax 来定义一个需要5.4 或更高版本的数组。

输出

array(5) {
  [0]=>
  string(3) "ggg"
  [1]=>
  string(3) "fff"
  [2]=>
  string(3) "eee"
  [3]=>
  string(3) "ddd"
  [4]=>
  string(3) "ccc"
}

现场示例

Repl

【讨论】:

    【解决方案3】:

    这应该可行:

        $arr = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
    
        $tmp = $arr;
        array_rand($tmp);
    
        $one = $tmp[0];
        $two = $tmp[1];
        ...
    

    请记住,它不会检查 $tmp[n] 中的值是否确实存在

    【讨论】:

      【解决方案4】:

      你可以使用PHP的shuffle函数来随机化数组中元素的顺序,然后取第一个元素。

      $randomArray = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
      shuffle($randomArray);
      
      $randomArray = array_slice($randomArray, 0, 5);
      
      $randomArray[0]; //1st element
      $randomArray[1]; //2nd element
      $randomArray[2]; //3rd element...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-18
        • 1970-01-01
        • 1970-01-01
        • 2014-04-16
        • 2018-09-19
        • 2012-03-27
        • 1970-01-01
        • 2022-12-01
        相关资源
        最近更新 更多