0

I want to manage my array but I haven't got any idea how I should to do it.

When I add a product I have many attributes that I can select like color, size. Sometimes I have more than 2 attributes.

$table = array(
    'color' => array('1', '2'),
    'size' => array('37', '38'),
    'other' => array('a', 'b'),
    ...
);

What I am looking for, is to have this result:

$table = array(
    '0' => array('1', '37','a'),
    '1' => array('1', '37','b'),
    '2' => array('1', '38','a'),
    '3' => array('1', '38','b'),
    '4' => array('2', '37','a'),
    '5' => array('2', '37','b'),
    '6' => array('2', '38','a'),
    '7' => array('2', '38','b'),
);    
mickmackusa
  • 43,625
  • 12
  • 83
  • 136

1 Answers1

2

Here is one approach to generating all combinations of a list of attributes and their options:

function generateCombinations(array $attributes)
{
    $combinations = array(array());
    foreach ($attributes as $options) {
        $new_combinations = array();
        foreach ($combinations as $combination) {
            foreach ($options as $option) {
                $new_combination = $combination;
                $new_combination[] = $option;
                $new_combinations[] = $new_combination;
            }
        }
        $combinations = $new_combinations;
    }
    return $combinations;
}

It works by iteratively building up a list of combinations for each attribute:

initialise: [[]]
1st attribute: [[1],[2]]
2nd attribute: [[1,37],[1,38],[2,37],[2,38]]
3rd attribute: [[1,37,a],[1,37,b],[1,38,a],[1,38,b],[2,37,a],[2,37,b],[2,38,a],[2,38,b]]
... and so on if there are additional attributes

You can call the function with your example data as follows:

$table = array(
    'color' => array('1', '2'),
    'size' => array('37', '38'),
    'other' => array('a', 'b'),
);
$combinations = generateCombinations($table);
var_dump($combinations);

Which gives the following output (tested with php 5.6):

array(8) {
  [0]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(2) "37"
    [2]=>
    string(1) "a"
  }
  [1]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(2) "37"
    [2]=>
    string(1) "b"
  }
// 6 other rows omitted ...
astrangeloop
  • 1,430
  • 2
  • 13
  • 11