开发者

php, how to jumble / randomize order of associative array while keeping key/value pairs

what is the p开发者_开发技巧hp function to randomize the associative array while keeping key/values pairs. I don't mean to just randomly pick out a key value pair, but actually changing the array (similar to the uasort function, but not in order).

TIA

example:

original array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)

random ordered array
(

[d] => -9
[a] => 4
[b] => 8
[c] => -1
[h] => -4   
[e] => 2
[g] => 3
[h] => -4
[f] => 5
)

Edit Comparison between 2 solutions.

$start = microtime(true);
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
$shuffleKeys = array_keys($array);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
    $newArray[$key] = $array[$key];
}
print_r ($newArray);
$elapsed = microtime(true) - $start;
echo "<br>array values took $elapsed seconds.<br>";

$start = microtime(true);
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
$keys = array_keys( $array );
   shuffle( $keys );
   print_r(array_merge( array_flip( $keys ) , $array ));


$elapsed = microtime(true) - $start;
echo "<br>array values took $elapsed seconds.<br>";

Array ( [h] => -4 [e] => 2 [b] => 8 [d] => -9 [a] => 4 [c] => -1 [f] => 5 [g] => 3 ) array values took 3.0994415283203E-5 seconds.

Array ( [e] => 2 [a] => 4 [d] => -9 [c] => -1 [g] => 3 [f] => 5 [b] => 8 [h] => -4 ) array values took 4.2915344238281E-5 seconds.


You could use shuffle() on array_keys, then loop around your array adding them to the list in the new order.

E.g.

$shuffleKeys = array_keys($array);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
    $newArray[$key] = $array[$key];
}


A comment on shuffle() might do the trick: http://ch2.php.net/manual/en/function.shuffle.php#104430

<?php
function shuffle_assoc( $array )
{
   $keys = array_keys( $array );
   shuffle( $keys );
   return array_merge( array_flip( $keys ) , $array );
}
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜