Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffle array by group of values

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 ?

like image 585
mimipc Avatar asked Jan 14 '23 03:01

mimipc


2 Answers

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);
like image 125
sectus Avatar answered Jan 25 '23 09:01

sectus


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);
like image 32
mimipc Avatar answered Jan 25 '23 08:01

mimipc