Skip to content

Instantly share code, notes, and snippets.

@veloxy
Created November 8, 2011 20:07
Show Gist options
  • Save veloxy/1349002 to your computer and use it in GitHub Desktop.
Save veloxy/1349002 to your computer and use it in GitHub Desktop.
Generate Combinations
<?php
function array_outer($f, array $array1) {
$res = array();
$arrays = $array1;
foreach ($arrays as $a) {
if (empty($a))
return $res;
}
$num_arrays = count($arrays);
$pos = array_fill(0, $num_arrays, 0);
while (true) {
$cur = array();
for ($i = 0; $i < $num_arrays; $i++) {
$cur[] = $arrays[$i][$pos[$i]];
}
$res[] = call_user_func_array($f, $cur);
for ($i = $num_arrays-1; $i >= 0; $i--) {
if ($pos[$i] < count($arrays[$i]) - 1) {
$pos[$i]++;
break;
} else {
if ($i == 0)
break 2;
$pos[$i] = 0;
}
}
}
return $res;
}
$f = function () { return func_get_args(); };
$res = array_outer($f, array( array("small", "medium", "big"),
array("blue", "red", "green", "pink"),
array("sunny", "cloudy", "snowy"),
array("sweet", "acid", "bitter", "edible")));
echo '<pre>'; var_dump($res); echo '</pre>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment