I'm looking for a way to shuffle an array by groups of values in PHP.
For example, I have a sorted array :
Array
(
[peter] => 100
[paul] => 100
[mary] => 50
[andrew] => 50
[bill] => 50
[jason] => 10
[sofia] => 10
)
And I'd like to shuffle it this way :
Array
(
[paul] => 100
[peter] => 100
[mary] => 50
[bill] => 50
[andrew] => 50
[jason] => 10
[sofia] => 10
)
Would you know a smart way to do this, or will I have to write a dirty foreach-based script ?
With this user defined function shuffle_assoc you can shuffle your array before sorting.
function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
$array = array('peter' => 100
, 'paul' => 100
, 'mary' => 50
, 'andrew' => 50
, 'bill' => 50
, 'jason' => 10
, 'sofia' => 10);
shuffle_assoc($array);
asort($array);
array_reverse($array);
var_dump($array);
I found the answer by using both arsort and the function shuffle_assoc() that is discribed in the first user contribution on this page : PHP: shuffle
function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
$array = array(
'peter' => 100,
'paul' => 100,
'mary' => 50,
'andrew'=> 50,
'bill' => 50,
'jason' => 10,
'sofia' => 10
);
shuffle_assoc($array);
arsort($array);
print_r($array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With