PHP Random Shuffle Array Maintaining Key => Value

后端 未结 10 1101
轮回少年
轮回少年 2020-11-27 19:21

I\'ve been looking on google for the answer but can\'t seem to find something fool-proof and cant really afford to mess this up (going live into a production site).

相关标签:
10条回答
  • 2020-11-27 20:00

    Try using the fisher-yates algorithm from here:

    function shuffle_me($shuffle_me) { 
       $randomized_keys = array_rand($shuffle_me, count($shuffle_me)); 
       foreach($randomized_keys as $current_key) { 
           $shuffled_me[$current_key] = $shuffle_me[$current_key]; 
       } 
       return $shuffled_me; 
    } 
    

    I had to implement something similar to this for my undergraduate senior thesis, and it works very well.

    0 讨论(0)
  • 2020-11-27 20:00

    Charles Iliya Krempeaux has a nice writeup on the issue and a function that worked really well for me:

    function shuffle_assoc($array)
    {
        // Initialize
            $shuffled_array = array();
    
    
        // Get array's keys and shuffle them.
            $shuffled_keys = array_keys($array);
            shuffle($shuffled_keys);
    
    
        // Create same array, but in shuffled order.
            foreach ( $shuffled_keys AS $shuffled_key ) {
    
                $shuffled_array[  $shuffled_key  ] = $array[  $shuffled_key  ];
    
            } // foreach
    
    
        // Return
            return $shuffled_array;
    }
    
    0 讨论(0)
  • 2020-11-27 20:03

    Answer using shuffle always return the same order. Here is one using random_int() where the order is different each time it is used:

    function shuffle_assoc($array)
    {
        while (count($array)) {
            $keys = array_keys($array);
            $index = $keys[random_int(0, count($keys)-1)];
            $array_rand[$index] = $array[$index];
            unset($array[$index]);
        }
    
        return $array_rand;
    }
    
    0 讨论(0)
  • 2020-11-27 20:06

    As of 5.3.0 you could do:

    uksort($array, function() { return rand() > rand(); });
    
    0 讨论(0)
提交回复
热议问题