4

I have array from input field, now what i want is to generate various combination of values to save in database colunm.

--------------------------------
id | value
--------------------------------
1  8,12,7,11
2   8,15,7,11
3   9,12,7,11
4   9,15,7,11
5   13,12,7,11
6   13,15,7,11

$first = $this->input->post('product_variant');

Array
(
[12] => Array
(
    [0] => 8
    [1] => 9
    [2] => 13
)

[13] => Array
(
    [0] => 12
    [1] => 15
)

[15] => Array
(
    [0] => 7
)

[16] => Array
(
    [0] => 11
)

)

now what i want to generate combination Like:

8,12,7,11
8,15,7,11
9,12,7,11
9,15,7,11
13,12,7,11
13,15,7,11
Vikas
  • 121
  • 1
  • 11
  • Do you want just a list of every variation? – AndrewL Sep 26 '16 at 03:23
  • Your question is unclear. SO will you please explain like on what basis you want to merge your array – Ankit Doshi Sep 26 '16 at 05:46
  • see like if: color: red, blue and size: s, m then it should generate 4 combination red-s, red-m, blue-s, blue-m: if color:red, blue, pink and size: s, m then it should generate 6: red-s, red-m, blue-s, blue-m, pink-s, pink-m. hope its clear now. – Vikas Sep 26 '16 at 06:29
  • 1
    This will help you: http://stackoverflow.com/a/28133030/916000 – Taha Paksu Sep 26 '16 at 07:54

2 Answers2

3

you use the multiple for loop, it will help you to generate that type of combinations.

Eg:

 for(int i=0;i<your array length;i++){
   for(int j=0;j<i;j++){

     //your code
  }
}

or try the below code

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;
}
Akhil
  • 379
  • 4
  • 14
2

This is Cartesian product.You can use this function

function cartesian($arr,$str = array()){
$first = array_shift($arr);
if(count($str) > 1) {
    foreach ($str as $k => $val) {
        foreach ($first as $key => $value) {
            $str2[] = $val.','.$value;
        }
    }
}else{
    foreach ($first as $key => $value) {
        $str2[] = $value;
    }
}

if(count($arr) > 0){
    $str2 = cartesian($arr,$str2);
}
return $str2;
}

Hope can help you.

nango
  • 61
  • 3