PHP Array Combinations
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
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
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];
}
}
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);
精彩评论