4

我正在寻找一种通过 PHP 中的值组对数组进行洗牌的方法。

例如,我有一个排序数组:

Array
(
    [peter] => 100
    [paul] => 100
    [mary] => 50
    [andrew] => 50
    [bill] => 50
    [jason] => 10
    [sofia] => 10
)

我想这样洗牌:

Array
(
    [paul] => 100
    [peter] => 100
    [mary] => 50
    [bill] => 50
    [andrew] => 50
    [jason] => 10
    [sofia] => 10
)

你知道一个聪明的方法来做到这一点,还是我必须编写一个肮脏的基于 foreach 的脚本?

4

2 回答 2

5

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);
于 2013-06-18T00:49:40.523 回答
4

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);
于 2013-06-18T00:50:08.447 回答