0

I have an arbitrary number of nested arrays in php. For example:

Array
(
    [0] => Array
        (
            [0] => 36
            [0] => 2
            [0] => 9
        )

    [1] => Array
        (
            [0] => 95
            [1] => 21
            [2] => 102
            [3] => 38
        )

    [2] => Array
        (
            [0] => 3
            [1] => 5
        )

)

I want to find the most efficient way to combine all possible combinations of each of these nested arrays. I'd like to end up with something that looks like this...

Array
(
    [0] => "36,95,3"
    [1] => "36,95,5"
    [2] => "36,21,3"
    [3] => "36,21,5"

    etc...

)

The order the results are combined in is not important. That is to say, there is no difference between "3,95,36", "36,95,3", and "95,36,3". I would like to omit these redundant combinations.

Any suggestions on how to go about this would be much appreciated.

Thanks in advance,

2
  • Is the depth arbitrary too? or just the number at a given depth? If the depth is known, you can loop like Josh Curren says - if not you'll have to do it recursively. Commented Mar 3, 2010 at 17:42
  • Do you always want triples or can this be 36,95 and 36,21,95,5 as well? Commented Mar 3, 2010 at 17:55

2 Answers 2

1
<?php
$a = array("01", "02");
$b = array("white", "green");
$c = array("one", "two", "three");
$aG = array($a, $b, $c);
$codes = array();
$pos = 0;
generateCodes($aG);

function generateCodes($arr) {
    global $codes, $pos;
    if(count($arr)) {
    for($i=0; $i<count($arr[0]); $i++) {
        $tmp = $arr;
        $codes[$pos] = $arr[0][$i];
        $tarr = array_shift($tmp);
        $pos++;
        generateCodes($tmp);

    }
    } else {
    echo join(", ", $codes)."<br/>";
    }
    $pos--;
}
?>
Sign up to request clarification or add additional context in comments.

Comments

0

General permutation solution for any number of groups (in Groovy to keep it simple).

list = [["A", "B", "W"], ["C", "D"], ["X", "Y"]]

r = []
void p(List<List<String>> l, int n) {
    for(t in l[n]) {
        r[n] = t
        if (n < l.size() - 1) {
            p(l, n + 1)
        } else {
            println(r)
        }
    }
}

p(list, 0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.