Shuffling the first level of an array in PHP

PHP shuffle() not randomizing an array the way I need it. I have a two-dimensional array, and when I use shuffle() , it only randomizes the 2-dimensional dimension of the array, but I need the opposite.

Suppose this is an array that I need to shuffle:

 Array ( [0] => Array ( [key1] => 199 [key2] => 6 ) [1] => Array ( [key1] => 195 [key2] => 3 ) ) 

By shuffling shuffle() it looks like this:

 Array ( [0] => Array ( [key1] => 195 [key2] => 3 ) [1] => Array ( [key1] => 199 [key2] => 6 ) ) 

But that is not what I need. Ultimately, I need the following:

 Array ( [1] => Array ( [key1] => 195 [key2] => 6 ) [0] => Array ( [key1] => 199 [key2] => 6 ) ) 

I know that this can be achieved using a random key with rand() or mt_rand() , but it is also possible that for a small number of keys we could get the same rand() key twice, NOT have a beautifully shuffled array.

I also know that adding if else logic would be possible, but I want to do this with material already implemented - I don't want to reinvent the wheel.

How can I achieve the desired shuffle?

0
source share
3 answers

shuffle() works as intended. This is not "randomization of the second dimension", it is not recursive.

It reorders the elements of the array (which just become arrays). The problem you see is that shuffle() resets array keys.

From the docs ( http://php.net/shuffle ):

Note This function assigns new keys to elements in the array. It will remove all existing keys that can be assigned, rather than simply reordering the keys.

To get what you want, you need to use array_rand() to randomize the keys, and then reorder the elements in the array based on this.

 $randKeys = array_rand($array, count($array)); // This is needed because array_rand was changed // and now returns the keys in order shuffle($randKeys); uksort($array, function($a, $b) use($randKeys){ return array_search($a, $randKeys) - array_search($b, $randKeys); }); 

DEMO: https://eval.in/101265

+3
source

In the comments section of the PHP shuffle manual you will find:

 <?php function shuffle_assoc(&$array) { $keys = array_keys($array); shuffle($keys); foreach($keys as $key) { $new[$key] = $array[$key]; } $array = $new; return true; } ?> 
0
source
 $yourArray = array( array('key1' => 199, 'key2' => 6), array('key1' => 195, 'key2' => 3), array('key1' => 205, 'key2' => 8) ); $helperArr = array(); foreach($yourArray as $subArr) { foreach($subArr as $key => $value) $helperArr[$key][] = $value; } foreach($helperArr as &$shuffleArr) shuffle($shuffleArr); $shuffledArr = array(); foreach($helperArr as $key => $value) { for($i = 0; $i < count($value); $i++) $shuffledArr[$i][$key] = $value[$i]; } echo '<pre>'; print_r($helperArr); print_r($shuffledArr); echo '</pre>'; 

Demo

0
source

All Articles