PHP,如何混杂/随机化关联数组的顺序,同时保持键/值对 [英] php, how to jumble / randomize order of associative array while keeping key/value pairs
问题描述
什么是php函数,用于在保持键/值对的同时随机化关联数组.我的意思不是要随机选择一个键值对,而是实际上要更改数组(类似于uasort函数,但不是按顺序排列).
what is the php 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
示例:
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>";
数组([h] => -4 [e] => 2 [b] => 8 [d] => -9 [a] => 4 [c] => -1 [f] => 5 [g] => 3) 数组值花费了3.0994415283203E-5秒.
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) 数组值花费了4.2915344238281E-5秒.
Array ( [e] => 2 [a] => 4 [d] => -9 [c] => -1 [g] => 3 [f] => 5 [b] => 8 [h] => -4 ) array values took 4.2915344238281E-5 seconds.
推荐答案
您可以在array_keys上使用shuffle(),然后循环遍历数组,以新顺序将它们添加到列表中.
You could use shuffle() on array_keys, then loop around your array adding them to the list in the new order.
例如
$shuffleKeys = array_keys($array);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
$newArray[$key] = $array[$key];
}
这篇关于PHP,如何混杂/随机化关联数组的顺序,同时保持键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!