1

I have to get all the combinations of values between n number of arrays.

Here is an example:

Filters: F1, F2, F3 contain values V1, V2, V3 the desire outcome is to have a massive array of all possible combinations in a such way:

V1^F1, V1^F2

V1^F1, V1^F2, V1^F3,

V1^F1, V1^F2, V2^F3

and so on.

The rules are that I don't need to combine the values inside a filter only with the values with the other arrays.

<?php

$filterA = array('blue', 'red', 'black');
$filterB = array('s', 'm', 'l');
$filterC = array('men', 'woman');


$filters[] = $filterA;
$filters[] = $filterB;
$filters[] = $filterC;

var_dump(combinations($filters));

function combinations($arrays, $i = 0)
{
     if (!isset($arrays[$i])) 
     {
            return array();
     }
        // Exit Conditions;
        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;
}

The following code produced almost the desired code however it misses to print out the 1st variation which is with less values.

Any suggestions to modify the code to get the desired outcome?

Unsparing
  • 6,985
  • 2
  • 17
  • 33

0 Answers0