Php 混合两个数组但不洗牌?
我想将两个数组合并/混合在一起,但我希望它是随机“混合”的,而不是混洗。例如:Php 混合两个数组但不洗牌?,php,arrays,sorting,merge,shuffle,Php,Arrays,Sorting,Merge,Shuffle,我想将两个数组合并/混合在一起,但我希望它是随机“混合”的,而不是混洗。例如: $first = array(1,2,3,4); $second = array(10,20,30,40); function zipShuffle($first, $second) { return call_user_func_array('array_merge', array_map(function($a, $b) { return mt_rand(0, 1) ? [$a, $b] : [$b
$first = array(1,2,3,4);
$second = array(10,20,30,40);
function zipShuffle($first, $second) {
return call_user_func_array('array_merge', array_map(function($a, $b) {
return mt_rand(0, 1) ? [$a, $b] : [$b, $a];
}, $first, $second));
}
可能的“混合”包括:
请注意,如果我们将这些值提取出来,我们仍将保留以下原始顺序:
1,2,3,4
10,20,30,40
有没有一种在php中快速实现这一点的方法?哼。也许像这样的事情会有用
//Loop this shit until both arrays are done
$j = 0;
$i = 0;
$r = rand(0, 1);
if($r == 0) {
$ret .= $array1[$i];
$i++;
} else if($r == 1) {
$ret .= $array2[$j];
$j++;
}
当然,您必须在这段代码中处理一些异常,但这可能是一条路线。嗯,还有一种可能的方法:
$arr = call_user_func_array('array_merge', array_map(null, $first, $second));
print_r($arr); // [1, 10, 2, 20, 3, 30, 4, 40];
。这显然是决定性的;对于随机排序,每一对都应另外洗牌。例如:
$first = array(1,2,3,4);
$second = array(10,20,30,40);
function zipShuffle($first, $second) {
return call_user_func_array('array_merge', array_map(function($a, $b) {
return mt_rand(0, 1) ? [$a, $b] : [$b, $a];
}, $first, $second));
}
。。。但这显然无法产生像[1,2,3,10,20…]
这样的东西。如果需要,这里有另一个解决方案:
function orderedShuffle($first, $second) {
$results = [];
$stor = [$first, $second];
$i = mt_rand(0, 1);
// switching between arrays on the fly
while (list(, $v) = each($stor[$i])) {
$results[] = $v;
$i = mt_rand(0, 1);
}
// one array is gone, now we need to add all the elements
// of the other one (as its counter left where it was)
$i = 1 - $i;
while (list(, $v) = each($stor[$i])) {
$results[] = $v;
}
return $results;
}
。最后一个函数实际上很容易扩展到所需的任意多个阵列。您能试试这个吗
<?php
$first = array(1,2,3,4);
$second = array(10,20,30,40);
$arrayMixed=array();
$firstReverse=array_reverse($first);
$secondReverse=array_reverse($second);
$firstReverseCount = count($firstReverse);
$secondReverseCount = count($secondReverse);
foreach($firstReverse as $key=>$val) {
if ($firstReverseCount>0) {
array_push($arrayMixed, array_pop($firstReverse));
if ($secondReverseCount>0) {
array_push($arrayMixed, array_pop($secondReverse));
}
}
}
$ArrayMixeddata = array_merge($arrayMixed, $second);
echo "<pre>";
print_r($ArrayMixeddata);
echo "</pre>";
?>
不是快速的方法,但它们很有效
//带排列
函数combineShuffleOrder($first,$second)
{
//交替组合成一个阵列
$firstLen=计数($first);
$secondLen=计数($second);
$max=max($firstLen,$secondLen);
$result=array();
对于($i=0;$i<$max;$i++){
如果($i<$firstLen)
$result[]=$first[$i];
如果($i<$secondLen)
$result[]=$second[$i];
}
//带排列的“洗牌”
$len=计数($result);
对于($i=1;$iI)来说,让这两个元素组成一个关联数组(使用array\u combine
)不是更好吗?你能定义随机“混合”
和shuffle
!