【发布时间】:2016-06-21 04:23:01
【问题描述】:
给定一个这样的关联数组,你如何打乱具有相同值的键的顺序?
array(a => 1,
b => 2, // make b or c ordered first, randomly
c => 2,
d => 4,
e => 5, // make e or f ordered first, randomly
f => 5);
我尝试的方法是把它变成这样的结构并对值(原始键的数组)进行洗牌,然后将其展平回原始形式。有没有更简单或更清洁的方法? (我不担心效率,这是针对小数据集的。)
array(1 => [a],
2 => [b, c], // shuffle these
4 => [d],
5 => [e, f]); // shuffle these
function array_sort_randomize_equal_values($array) {
$collect_by_value = array();
foreach ($array as $key => $value) {
if (! array_key_exists($value, $collect_by_value)) {
$collect_by_value[$value] = array();
}
// note the &, we want to modify the array, not get a copy
$subarray = &$collect_by_value[$value];
array_push($subarray, $key);
}
arsort($collect_by_value);
$reordered = array();
foreach ($collect_by_value as $value => $array_of_keys) {
// after randomizing keys with the same value, create a new array
shuffle($array_of_keys);
foreach ($array_of_keys as $key) {
array_push($reordered, $value);
}
}
return $reordered;
}
【问题讨论】:
标签: php arrays sorting random associative-array