dougaoshang0237 2019-07-01 10:14
浏览 172
已采纳

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

I have two array like these:

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

I want all the combination of strings like these:

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

How to do this in php?

PS - array can be of any length but both arrays size are always same.

PPS - The accepted answer given in this question is not giving me the correct result. It is giving the following result:

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条回答 默认 最新

  • dqsw7529 2019-07-01 10:30
    关注

    You need to convert your array to this,

    $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."
    ";
    }
    

    Once you convert your array using array_map, then I used help of this.

    Demo.

    Output

    abc defs ghi
    abc defs ghis
    abc def ghi
    abc def ghis
    abcs defs ghi
    abcs defs ghis
    abcs def ghi
    abcs def ghis
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?