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条)

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统