0

I am working on a feature where I need to generate combination from multiple array items, for example:

array_one('Size:S', 'Size:M');
array_two('Color:Red', 'Color:Yellow');
array_three('Brand:Hugo','Brand:Boss');

And expected combination should be like below:
Combination_one: Size:S,Color:Red,Brand:Hugo
Combination_two: Size:S,Color:Red,Brand:Boss
Combination_three: Size:S,Color:Yellow,Brand:Hugo
Combination_four: Size:S,Color:Yellow,Brand:Boss

Combination_five: Size:M,Color:Red,Brand:Hugo
Combination_six: Size:M,Color:Red,Brand:Boss
Combination_seven: Size:M,Color:Yellow,Brand:Hugo
Combination_eight: Size:M,Color:Yellow,Brand:Boss

How can I do that using PHP?

halfer
  • 19,471
  • 17
  • 87
  • 173
leaveme_alone
  • 496
  • 2
  • 5
  • 18
  • You are looking for [Cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) – Joseph Wood Aug 31 '18 at 18:49
  • Yes, it is. Can you please help on it? – leaveme_alone Aug 31 '18 at 18:53
  • There are several algorithm outlines on the web for generating this. I'm not sure how to do it in `php`, but I will say if you know that you will only have 3 arrays, you can easily write 3 nested for loops and iterate over each array. I don't recommend this as there are much better more general approaches, but I just wanted to let you know to get your head around how to complete your task. – Joseph Wood Aug 31 '18 at 18:57
  • Would `rand()` be of any use to you? – treyBake Aug 31 '18 at 18:58
  • 1
    @ThisGuyHasTwoThumbs, could you explain why `rand()` would be useful here? – Joseph Wood Aug 31 '18 at 19:00
  • @Joseph sure - you use rand to get a random result from each array and combine that into a string :) though re-looking at the desired results... Maybe a loop as you've suggested in the comment is best. Just loop over the arrays and add to one array and foreach that – treyBake Aug 31 '18 at 19:03
  • @ThisGuyHasTwoThumbs, that is what I thought you were hinting at, but given the small number of outcomes, it would be easy enough to generate them all. – Joseph Wood Aug 31 '18 at 19:04
  • @Joseph true that :) – treyBake Aug 31 '18 at 19:04
  • If you have only three arrays, do it with FOR loops. If you have more, than they cannot have all different names. Make a matrix and use recursion. – vladatr Aug 31 '18 at 19:14
  • Guys, I managed to solve it. – leaveme_alone Sep 01 '18 at 06:09
  • Here comes solution: function generateCombinations($arrays, $index = 0) { if (!isset($arrays[$index])) { return array(); } if ($i == count($arrays) - 1) { return $arrays[$index]; } $temp = generateCombinations($arrays, $index + 1); $results = array(); foreach($arrays[$index] as $val) { foreach ($temp as $t_val) { $results[] = is_array($t_val) ? array_merge(array($val), $t_val) : array($val, $t_val); } } return $results; } print_r( generateCombinations(array( ) )); – leaveme_alone Sep 01 '18 at 06:14

0 Answers0