Skip to content
Advertisement

infinite array loop and combine with other array in loop [PHP]

First, I don’t know is it my question title is correct or not, I’m sorry if I make any confuse.

So I have a set of array which I need to combine on tree method to become any possible new set of array.

here is my array:

$layer = array(
                array(18,19,20,21,22),
                array(1,2,7,8,14),
                array(3,4,9,10,15),
                array(5,6,12,13,16),
                array(11),
                array(17)
            )

what I’m expecting is combining those array value to become new set of array with tree method combination.

Array (
    [0] => 18-1-3-5-11-17
    [1] => 18-1-3-6-11-17
    [2] => 18-1-3-12-11-17
    [3] => 18-1-3-13-11-17
    [4] => 18-1-3-16-11-17
    [5] => 18-1-4-5-11-17
    [6] => 18-1-4-6-11-17
    [7] => 18-1-4-12-11-17
    ........
    ........
    ........
    [x] => 22-14-15-16-11-17
)

As you see above, the combination could be as much as how much array values combined each other.

I can easily combine two array with below code:

$i = 0;
$arr = array();

for ($x = 0; $x < count($layer_files[$i]); $x++) {
    for ($y = 0; $y < count($layer_files[($i + 1)]); $y++) {
        $arr[] = $layer_files[$i][$x] . '-' . $layer_files[($i + 1)][$y];
    }
}
$i++;

But, I have no idea how to combine more than two array as I expected above.

Hopefully you understand what I trying to ask, thank you for your help.

Advertisement

Answer

You can use recursion:

function combinations($sets, $i=0) {
    if ($i >= count($sets)) return [[]];
    foreach($sets[$i] as $value) {
        foreach(combinations($sets, $i + 1) as $combi) {
            $results[] = [$value, ...$combi];
        }
    }
    return $results;
}

$matrix = combinations($layer);
// Convert each combination to a string (using "-" separator)
foreach($matrix as $combo) {
    $results[] = implode("-", $combo);
}

$results will have the desired structure.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement