在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中文網其他相關文章!