首页 >后端开发 >php教程 >如何在 PHP 中从多个数组生成项目的所有组合?

如何在 PHP 中从多个数组生成项目的所有组合?

Patricia Arquette
Patricia Arquette原创
2024-12-14 13:46:12724浏览

How Can I Generate All Combinations of Items from Multiple Arrays in PHP?

在 PHP 中生成多个数组中项目的所有组合

在编程中经常遇到查找多个数组中项目的所有组合的任务。数组和每个数组中元素的数量可能会有所不同。

递归解决方案

递归方法可以有效解决这个问题。 Combinations() 函数提供了一个解决方案:

function combinations($arrays, $i = 0) {
    if (!isset($arrays[$i])) {
        return array();
    }
    if ($i == count($arrays) - 1) {
        return $arrays[$i];
    }

    // get combinations from subsequent arrays
    $tmp = combinations($arrays, $i + 1);

    $result = array();

    // concat each array from tmp with each element from $arrays[$i]
    foreach ($arrays[$i] as $v) {
        foreach ($tmp as $t) {
            $result[] = is_array($t) ? array_merge(array($v), $t) : array($v, $t);
        }
    }

    return $result;
}

用法示例

考虑数组:

$arrayA = array('A1','A2','A3');
$arrayB = array('B1','B2','B3');
$arrayC = array('C1','C2');

查找所有组合:

print_r(combinations(array($arrayA, $arrayB, $arrayC)));

输出:

Array
(
    [0] => A1
    [1] => B1
    [2] => C1
    [3] => A1
    [4] => B1
    [5] => C2
    [6] => A1
    [7] => B2
    [8] => C1
    [9] => A1
    [10] => B2
    [11] => C2
    [12] => A1
    [13] => B3
    [14] => C1
    [15] => A1
    [16] => B3
    [17] => C2
    [18] => A2
    [19] => B1
    [20] => C1
    [21] => A2
    [22] => B1
    [23] => C2
    [24] => A2
    [25] => B2
    [26] => C1
    [27] => A2
    [28] => B2
    [29] => C2
    [30] => A2
    [31] => B3
    [32] => C1
    [33] => A2
    [34] => B3
    [35] => C2
    [36] => A3
    [37] => B1
    [38] => C1
    [39] => A3
    [40] => B1
    [41] => C2
    [42] => A3
    [43] => B2
    [44] => C1
    [45] => A3
    [46] => B2
    [47] => C2
    [48] => A3
    [49] => B3
    [50] => C1
    [51] => A3
    [52] => B3
    [53] => C2
)

此解决方案以有效的方式提供所有可能的组合。

以上是如何在 PHP 中从多个数组生成项目的所有组合?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn