views:

300

answers:

4

Hi Guys, Im using the accepted answer in this question. As I have the same requirements, I need to get all combinations of an array of variable length with a variable number of elements. However I also need it to produce all combinations which don't use all the elements of the array, but are in order. If that makes sense?

So if this is the array:

$array = array(
    array('1', '2'),
    array('a', 'b', 'c'),
    array('x', 'y'),
);

I also want it to add like 1a, 1b, 1c, 2a, 2b, 2c. But not 1x or 1y, because it misses out the second element of the array.

I can't quite figure out how to change the answer to include this.

Thanks, Psy

A: 

Something like this? The idea is to loop one array, and combine with each value in another array.

// Loop array[0].
for($i=0; $i<count($array[0]); $i++) {
 // Loop array[1]
 for($j=0; $j<count($array[1]); $j++) {
  echo $array[0][$i];
  echo $array[1][$j];
 }
}
Kristoffer Bohmann
I doubt the array(s) will have a fixed length.
Bart Kiers
A: 

Maybe you could describe what you're trying to achieve with a realistic example? Your way of describing your problem/solution is quite abstract and I'm not sure what you're looking for, keeping the other posted comments in mind...

Ben Fransen
+1  A: 

Using Josh Davis' approach in the answer to the linked question:

    $array = array( array('1', '2'), 
                    array('a', 'b', 'c'), 
                    array('m', 'n'), 
                    array('x', 'y'));

    $result = array();
    $php = 'list($a' . implode(',$a', array_keys($array)) . ')=$array;';
    $close_brakets='';
    $r='';
    foreach($array as $k => $v)
    {
        $r .= '$v'.$k;
        $php.='foreach($a'.$k.' as $v'.$k.'){ $result[]="'.$r.'";';
        $close_brakets.="}";
    }

    $php .= $close_brakets;

    eval($php);

    print_r($result);

gives you the desired combinations

danii
Thanks must not have tried that code, I actually managed to take my current code and change it in the end, however this does work aswell :)
Psytronic
A: 

Well taking the code that I was originally using, this is what I came up with, just incase anyone else is curious

$patterns_array = array();

$php = '';
foreach ($patterns as $i = > $arr)
{
    $php .= 'foreach ($patterns[' . $i . '] as $k' . $i . ' => $v' . $i . '){';
    $tmp = array();
    for($ii=1; $ii<=$i; $ii++){
     $tmp[] = $ii; 
    }
    $php .= '$patterns_array[] = $v'.implode('."::".$v', $tmp).';';
}

$php .= '$patterns_array[] = $v' . implode('."::".$v', array_keys($patterns)) . ';' . str_repeat('}', count($patterns));

eval($php);
Psytronic