dsfds2353 2018-06-07 14:06
浏览 49
已采纳

从数组中选择五个唯一的随机PHP值,并将它们放在单独的变量中

I have an array, for example:

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

I want to select five random and unique values from it and put them in five different variables, for example:

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

I have already found this code below which works for generating the random strings and just displaying them, but the output I want is for getting them in different variables and being able to use them separately.

<?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;
 }
  • 写回答

4条回答 默认 最新

  • dongye1934 2018-06-07 14:10
    关注

    You can shuffle the array and use list to assign the values

    $arr = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
    
    shuffle( $arr );
    list($one, $two, $three, $four, $five) = $arr;
    

    Doc: shuffle(), list()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码