PHP Random Shuffle Array Maintaining Key => Value

后端 未结 10 1213
轮回少年
轮回少年 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

    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;
    }
    

提交回复
热议问题