I'im trying to find all combinations of items in several arrays. The number of arrays is random (this can be 2, 3, 4, 5...). The number of elements in each array is random too...
For exemple, I have the 3 arrays :
$arrayA = array('A1','A2','A3');
$arrayB = array('B1','B2','B3');
$arrayC = array('C1','C2');
I would like to generate an array with 3 x 3 x 2 = 18 combinations :
- A1, B1, C1
- A1, B1, C2
- A1, B2, C1
- A1, B2, C2
- A1, B3, C1
- A1, B3, C2
- A2, B1, C1
- A2, B1, C2 ...
The problem is to create a function with a variable number of source arrays...
This code besides simplicity, get all combinations of multiple arrays and preserves keys.
Exemple:
Will return:
One more idea:
This is a cartesian product, and I just asked the same question not too long ago. Here is the algorithm that is posted on the PHP website.
Here is recursive solution:
I know this question is old, but I got the same issue today and decided to give the new Generator a try:
Result: