从PHP中的两个数组生成所有组合

时间:2019-07-01 10:14:56

标签: php arrays

我有两个像这样的数组:

$a = array("abc","defs","ghi");
$b = array("abcs","def","ghis");

我想要所有这样的字符串组合:

abc defs ghi
abc def ghi
abc def ghis
abc defs ghis
abcs defs ghi
abcs def ghi
abcs def ghis
abcs defs ghis

如何在php中做到这一点?

PS-数组可以是任意长度,但是两个数组的大小始终相同。

PPS-this question中给出的可接受答案没有给我正确的结果。结果如下:

Array ( [0] => Array ( [0] => abc [1] => abcs ) [1] => Array ( [0] => abc [1] => def ) [2] => Array ( [0] => abc [1] => ghi ) [3] => Array ( [0] => defs [1] => abcs ) [4] => Array ( [0] => defs [1] => def ) [5] => Array ( [0] => defs [1] => ghi ) [6] => Array ( [0] => ghi [1] => abcs ) [7] => Array ( [0] => ghi [1] => def ) [8] => Array ( [0] => ghi [1] => ghi ) ) 

1 个答案:

答案 0 :(得分:1)

您需要将数组转换为此,

$a    = ["abc", "defs", "ghi"];
$b    = ["abcs", "def", "ghis"];
$temp = array_map(null, $a, $b); // this conversion we call it transposing of array
function combinations($arrays)
{
    $result = [];
    $arrays = array_values($arrays);
    $sizeIn = sizeof($arrays);
    $size   = $sizeIn > 0 ? 1 : 0;
    foreach ($arrays as $array) {
        $size = $size * sizeof($array);
    }
    for ($i = 0; $i < $size; $i++) {
        $result[$i] = [];
        for ($j = 0; $j < $sizeIn; $j++) {
            array_push($result[$i], current($arrays[$j]));
        }
        for ($j = ($sizeIn - 1); $j >= 0; $j--) {
            if (next($arrays[$j])) {
                break;
            } elseif (isset($arrays[$j])) {
                reset($arrays[$j]);
            }
        }
    }
    return $result;
}
$res = combinations($temp);
// imploding all the values internally with space
$temp = array_map(function($item){
    return implode(" ", $item);
},$res);
// looping to show the data
foreach($temp as $val){
    echo $val."\n";
}

使用array_map转换数组后,我就使用了this的帮助。

Demo

输出

abc defs ghi
abc defs ghis
abc def ghi
abc def ghis
abcs defs ghi
abcs defs ghis
abcs def ghi
abcs def ghis