【发布时间】:2015-11-16 23:30:39
【问题描述】:
您好,我有一个集合或数组:
$arr = ['1','2','3','4','5','6','7','8','9','0'];
shuffle($arr);
这将返回数组的随机顺序。但是如果'3','4' 和'8','9','0' 必须在一起,我该如何编码?我的意思是其他值可以随机排列,但这些 '3','4' 和 '8','9','0' 必须连接在一起。
【问题讨论】:
您好,我有一个集合或数组:
$arr = ['1','2','3','4','5','6','7','8','9','0'];
shuffle($arr);
这将返回数组的随机顺序。但是如果'3','4' 和'8','9','0' 必须在一起,我该如何编码?我的意思是其他值可以随机排列,但这些 '3','4' 和 '8','9','0' 必须连接在一起。
【问题讨论】:
另一种方法是先获取这些有序元素(另一个副本),然后将原始元素打乱,然后使用 union 再次合并它们:
$arr = ['1','2','3','4','5','6','7','8','9','0'];
$arr2 = array_filter($arr, function($e){ // get those elements you want preversed
return in_array($e, [3, 4, 8, 9, 0]);
});
shuffle($arr); // shuffle the original
$ordered = $arr2 + $arr; // use union instead of array merge
ksort($ordered); // sort it by key
print_r($ordered);
【讨论】:
许多可能的解决方案,一个例子
<?php
$arr = ['1','2',['3','4'],'5','6','7',['8','9','0']];
shuffle($arr);
// and then flatten the array ..somehow, e.g.
array_walk_recursive($arr, function($e) { echo $e, ' '; });
【讨论】: