du7999 2013-01-21 05:18 采纳率: 100%
浏览 27
已采纳

PHP:从数组中重复选择

In my php script, I have a variable $data that contains an array that may have various number of elements.

The script picks one of the array elements at random and outputs it to the browser:

# count number of elements in $data
$n = count($data);

# pick a random number out of the number of elements in $data
$rand = rand(0, ($n - 1));

# output a random element
echo '<p> . trim($data[$rand]) . '</p>';

QUESTION: I want to improve that script, so that it doesn't output the same array element again until it runs out of array elements. For example, if an array contains elements numbered 0 to 9, and the script picked an array element #4, I want it to remember that, and next time the script runs, to exclude the element that was #4.

It could probably be done in many different ways, but I'm looking for the simplest and most elegant solution, and would be grateful for help from a PHP expert.

  • 写回答

4条回答 默认 最新

  • dongpeiwei8589 2013-01-21 05:24
    关注

    Save the numbers that were already picked in the user's session.

    session_start();
    $n = count($data); 
    
    // If the array isn't initialized, or we used all the numbers, reset the array
    if( !isset( $_SESSION['used_nums']) || count( $_SESSION['used_nums']) == $n) {
        $_SESSION['used_nums'] = array();
    }
    
    do{ 
        $rand = rand(0, ($n - 1));
    } while( isset( $_SESSION['used_nums'][$rand]));
    
    echo '<p>' . trim($data[$rand]) . '</p>';    
    $_SESSION['used_nums'][$rand] = 1;
    

    Or, perhaps a more clever way, using array_intersect_key and array_rand:

    session_start();
    $n = count($data); 
    
    // If the array isn't initialized, or we used all the numbers, reset the array
    if( !isset( $_SESSION['used_nums']) || count( $_SESSION['used_nums']) == $n) {
        $_SESSION['used_nums'] = array();
    }
    
    $unused = array_intersect_key( $data, $_SESSION['used_nums'];
    $rand = array_rand( $unused);
    
    echo '<p>' . trim($unused[$rand]) . '</p>';    
    $_SESSION['used_nums'][$rand] = 1;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题