php,如何在保持键/值对的同时混淆/随机化关联数组的顺序

时间:2011-09-18 18:55:35

标签: php associative-array

什么是在保持键/值对的同时随机化关联数组的php函数。我并不是要随机选择一个键值对,而是实际更改数组(类似于uasort函数,但不是按顺序)。

TIA

示例:

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
)

编辑 两种解决方案的比较。

$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>";

阵列([h] =&gt; -4 [e] =&gt; 2 [b] =&gt; 8 [d] =&gt; -9 [a] =&gt; 4 [c] =&gt; -1 [f] =&gt; 5 [g] =&gt; 3) 数组值为3.0994415283203E-5秒。

阵列([e] =&gt; 2 [a] =&gt; 4 [d] =&gt; -9 [c] =&gt; -1 [g] =&gt; 3 [f] =&gt; 5 [ b] =&gt; 8 [h] =&gt; -4) 数组值花了4.2915344238281E-5秒。

2 个答案:

答案 0 :(得分:7)

您可以在array_keys上使用shuffle(),然后在数组中循环,将它们按新顺序添加到列表中。

E.g。

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

答案 1 :(得分:4)

shuffle()的评论可能会解决问题: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 );
}
?>