PHP calculates each permutation from a two dimensional array

I searched and scratched my head for days and I was stuck between a rock and a hard place. After all my previous codes are executed, I am left with this array:

Array ( 
    [0] =>  Array
    (
        [0] => 1
        [1] => 3
    ) 
    [1] => Array 
    (
        [0] => 6
        [1] => 7 
        [2] => 8
    ) 
    [2] => Array 
    ( 
        [0] => 9 
        [1] => 10 
    ) 
)

      

What I need to do is calculate every possible permutation of all keys.

The desired result should be easily inserted as separate records or preferably a bulk insert into sql database.

After my hunt, I have tried countless examples. The closest I got was using the Implode function, but that still won't work.

Any help is greatly appreciated!

- Edit -

Here's an example of what the returned array should look like:

Array
(
    [0] => 1,6,9
    [1] => 1,6,10
    [2] => 3,6,9
    [3] => 3,6,10
    [4] => 1,7,9
    [5] => 1,7,10
    [6] => 3,7,9,
    [7] => 3,7,10
)

      

This is not every permutation, but should give you an idea of ​​what I need to achieve.

+3


source to share


1 answer


What you are trying to do is defined in this formula: permutation formula

And it can be done like this, it is called a Cartesian product:



function cartesian() {
    $_ = func_get_args();
    if(count($_) == 0)
        return array(array());
    $a = array_shift($_);
    $c = call_user_func_array(__FUNCTION__, $_);
    $r = array();
    foreach($a as $v)
        foreach($c as $p)
            $r[] = array_merge(array($v), $p);
    return $r;
}

$count = cartesian(
    Array(1,3),
    Array(6,7,8), 
    Array(9,10)
);

print_r($count);

      

+5


source







All Articles