Question

I need to combine some elements.

What I have:

Array
(
    [0] => Array
        (
            [0] => n
            [1] => q
        )

    [1] => Array
        (
            [0] => d
            [1] => g
        )
)

What I need:

n d
n g
q d
q g

How can I archive this?

As you can see there are two groups. But this will be dynamic It can be as many groups as I want, and as many elements by group as I want.

For ex:

Array
(
    [0] => Array
        (
            [0] => n
            [1] => q
            [2] => x
            [3] => b
        )

    [1] => Array
        (
            [0] => d
            [1] => g
            [2] => q
            [3] => w
        )

    [2] => Array
        (
            [0] => x
            [1] => y
            [2] => a
            [3] => c
        )
)

Just an example, because there are a lot:

n d x
n g y
n q a
n w c

n d y
n g a
n q c
n w x

n d a
n g c
n q x
n w y

n d c
n g x
n q y
n w a

n g x
n q y
n w a
n d c

n g y
n q a
n w c
n d x

n g a
n q c
n w x
n d y

n g c
n q x
n w y
n d a 

Now we have to start with q to replace n, an so on.

I hope someone can help me.

Thanks!

Was it helpful?

Solution

Checkout the following code. It gives you all the permutations that you require.

<?php
//$arr = array(
//  array('a', 'b', 'c', 'd'),
//  array('e', 'f', 'g', 'h'),
//  array('p', 'q', 'r', 's')
//);
$arr = array(
    array('n', 'q'),
    array('d', 'g')
);

$permutations = $arr[0];

for ($i = 1; $i < count($arr); $i++)
{
    $inner_temp = array();
    for ($k = 0; $k < count($permutations); $k++)
    {
        for ($j = 0; $j < count($arr[$i]); $j++)
            array_push($inner_temp, $permutations[$k] . $arr[$i][$j]);
    }
    $permutations = $inner_temp;
}

echo "<pre>";
print_r($permutations);
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top