PHP中两个数组的完全唯一组合

PHP中两个数组的完全唯一组合,php,arrays,Php,Arrays,我一整天都在为这个问题苦苦挣扎,我无法想出一个可行的解决方案,既不需要大量的内存,也不需要花很长时间才能完成 如果我有两个数组: $letters = array ('a','b','c','d'); $numbers = array (1,2,3,4); 如何获得完全独特的组合?换句话说,因为这些数组每个都有四个元素,所以函数应该只返回四个组合,数组中的每个元素只使用一次 使用上述阵列的示例组合: a1 b2 c3 d4 -或- a2 b4 c3 d1 -或- a4 b2 c3 d1 ……

我一整天都在为这个问题苦苦挣扎,我无法想出一个可行的解决方案,既不需要大量的内存,也不需要花很长时间才能完成

如果我有两个数组:

$letters = array ('a','b','c','d');

$numbers = array (1,2,3,4);
如何获得完全独特的组合?换句话说,因为这些数组每个都有四个元素,所以函数应该只返回四个组合,数组中的每个元素只使用一次

使用上述阵列的示例组合:

a1 b2 c3 d4

-或-

a2 b4 c3 d1

-或-

a4 b2 c3 d1

……等等

我发现的所有示例都没有考虑两个数组的唯一性。这样的答案是无效的:

a1 b2 c3 d3

-或-

a3 b2 c3 d2


我花了很长时间来制作一个能正常工作的函数。

假设两个数组的长度都与您的示例中相同,可能类似于这样,使用:


另一种不预先洗牌数组的可能性(并不是说这有什么问题;只是另一种方法):


您是要获取所有的唯一组合,还是仅获取一组随机的唯一组合?一组组合,其中两个数组中的每个元素只使用一次。您确定吗?我使用它时得到了不同的结果
<?php

$letters = array ('a','b','c','d');
$numbers = array (1,2,3,4);

function randmix($a, $b){
    shuffle($a);
    shuffle($b);
    foreach($a as $i => $val){
        $product []= $val.$b[$i];
    }
    return $product;
}

print_r(randmix($letters,$numbers));
Array
(
    [0] => d1
    [1] => a3
    [2] => c4
    [3] => b2
)
while ($letters && $numbers) {              // keep going as long as both arrays have values
    $combination = '';
    foreach ([&$letters, &$numbers] as &$array) {

        // select a random element from each array and then unset it
        $key = array_rand($array);
        $combination .= $array[$key];
        unset($array[$key]);
    }
    $combinations[] = $combination;
}