dongtuan5367 2016-11-24 21:22
浏览 24
已采纳

PHP返回随机数组

I am trying to create a new array from an existing one with a random number of records between 2 and 10, I have this so far

//Select a random number
$random_number = (rand(2,10));

// Setup an array of names
$names = array("john", "joe", "simon", "peter", "paul");

// Create new array
$random_field_names = array_rand($names, $random_number);

print_r($random_field_names);

This gives me an array that looks like this

Array
(
    [0] => 0
    [1] => 10
    [2] => 11
)

Where am I going wrong?

  • 写回答

3条回答 默认 最新

  • dongtang5057 2016-11-24 21:31
    关注

    The description of array_rand explains why you don't get the names (I stress in bold):

    Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

    You seem to want the values. That you can achieve like this:

     array_intersect_key($names,  array_flip(array_rand($names, $random_number)));
    

    Also make sure your random number is not greater than the array size:

    $random_number = rand(2,5);
    $names = array("john", "joe", "simon", "peter", "paul");
    $result = array_intersect_key($names,  array_flip(array_rand($names, $random_number)));
    print_r ($result);  
    

    Note that the result maintains the original keys. If you want to renumber the keys to get an indexed array starting with index 0, then apply array_values to the result:

    $result = array_values(array_intersect_key($names,  array_flip(array_rand($names, $random_number))));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决