Home >Backend Development >PHP Tutorial >How Can I Generate All Combinations of Items from Multiple Arrays in PHP?
Generating All Combinations of Items in Multiple Arrays in PHP
The task of finding all combinations of items in multiple arrays is encountered often in programming. The number of arrays and elements within each array may vary.
Recursive Solution
A recursive approach can effectively address this problem. The combinations() function provides a solution:
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; }
Example Usage
Consider the arrays:
$arrayA = array('A1','A2','A3'); $arrayB = array('B1','B2','B3'); $arrayC = array('C1','C2');
To find all combinations:
print_r(combinations(array($arrayA, $arrayB, $arrayC)));
Output:
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 )
This solution provides all possible combinations in an efficient manner.
The above is the detailed content of How Can I Generate All Combinations of Items from Multiple Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!