2

I've got three dynamically filled arrays. It's possible that only one or two arrays have data.

$array1 = array(
    [0] => 100GB
    [1] => 500GB
)

$array2 = array(
    [0] => black
    [1] => yellow
    [2] => green
)

$array1 = array(
    [0] => 2.5"
)

No I need to combine them into a new array that includes all possible variations

$variations = array(
    [0] => 100GB - black - 2.5"
    [1] => 100GB - yellow - 2.5"
    [2] => 100GB - green - 2.5"
    [3] => 500GB - black - 2.5"
    [4] => 500GB - yellow - 2.5"
    [5] => 500GB - green - 2.5"
)

Until now I didn't find a way to do this. Can someone please help me?

Thank you in advance

invictus
  • 825
  • 1
  • 9
  • 33

2 Answers2

7

You can achieve this easily with foreach loops:

$array1 = array('100GB', '500GB');
$array2 = array('black', 'yellow', 'green');
$array3 = array('2.5');

$combinations = array();
foreach ($array1 as $i) {
  foreach ($array2 as $j) {
    foreach ($array3 as $k) {
      $combinations[] = $i.' - '.$j.' - '.$k;
    }
  }
}

echo implode("\n", $combinations);

Edit: To handle empty arrays, you could use this function:

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;
}

This function was taken from this answer, so credit goes to the author. You can then call this combinations function this way:

$array1 = array('100GB', '500GB');
$array2 = array();
$array3 = array('2.5');

$arrays = array_values(array_filter(array($array1, $array2, $array3)));
$combinations = combinations($arrays);

foreach ($combinations as &$combination) {
  $combination = implode(' - ', $combination);
}

echo implode("\n", $combinations);

This outputs:

100GB - 2.5
500GB - 2.5
Community
  • 1
  • 1
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
  • hi, thank you that'S solving it partly. The problem is, if there's no array3 thann $result is empty. how can I avoid this? – invictus Jun 29 '14 at 18:41
  • perhapse you can also have an eye on here http://stackoverflow.com/questions/24499295/dynamically-create-new-arrays-fill-each-with-specials-values-from-first-array-a – invictus Jun 30 '14 at 21:36
0

You just need to use nested loops. One loop on the first array, one on the second, one on the third, and join the items from each array, and push the result onto a new array.

jcaron
  • 17,302
  • 6
  • 32
  • 46