How to combine array value?

I have an array from the input field, now I want to create a different combination of values ​​to store in the colunm database.

--------------------------------
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 a Like combination:

8,12,7,11
8,15,7,11
9,12,7,11
9,15,7,11
13,12,7,11
13,15,7,11
+4
source share
2 answers

This is a Cartesian work. 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.

+2
source

you are using a multiple for loop, this will help you generate this type of combination.

For instance:

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

     //your code
  }
}

or try the code below

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;
}
+3
source

Source: https://habr.com/ru/post/1655781/


All Articles