我有一个数组,其中类似的值靠得很近。像:
1: Apple 2: Big Apple 3: Small Apple 4: Green Apple 5: Orange 6: Small Orange 7: Ripe Orange
等
如果我打电话给shuffle,安排可能会改为:
1: Apple 3: Small Apple 5: Orange 4: Green Apple 6: Small Orange 2: Big Apple 7: Ripe Orange
正如你所看到的,大多数苹果仍在一起。当有10种相似类型的元素时,这会变得更糟。有没有办法正确随机化每个值的位置?怎么样多次调用shuffle。还有其他更好的方法吗?
答案 0 :(得分:0)
假设程序是从每个项目的最后一个单词中学习那种,这就是解决方案。 (如果不是,只需更改kind_of()
功能中的逻辑)
<?php
// learn what kind if item is it
function kind_of($item) {
$words = explode(' ', $item);
return array_pop($words);
}
// reorganize as 2-dimensional array
function by_kind($input) {
$output = array();
foreach ($input as $item) {
$output[kind_of($item)][] = $item;
}
return $output;
}
$input = array(
'Orange',
'Apple',
'Big Apple',
'Small Orange',
'Small Apple',
'Ripe Orange',
'Green Apple',
);
// arrange the items in 2-dimensional by_kind array
// then shuffle each second level arrays
$by_kind = by_kind($input);
ksort($by_kind); // sort by key (kind name)
$shuffled_by_kind = array_map(function ($kind_items) {
shuffle($kind_items);
return $kind_items;
}, $by_kind);
// merge the second level arrays back to 1 array
$result = call_user_func_array('array_merge', array_values($shuffled_by_kind));
// see output
var_dump($result);
答案 1 :(得分:0)
这是您需要的工作示例:
public function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
$fruits = array(
1 => 'Apple ',
2 => 'Big Apple ',
3 => 'Small Apple ',
4 => 'Green Apple ',
5 => 'Orange ',
6 => 'Small Orange ',
7 => 'Ripe Orange',
);
shuffle_assoc($fruits);
echo "<pre>"; var_dump($fruits); die;