Created
May 14, 2017 08:23
-
-
Save alixcan/47561ee492c1bd517fe0a4ccc2b66b7f to your computer and use it in GitHub Desktop.
PHP array combinations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function combinations($arrays, $i = 0) { | |
if (!isset($arrays[$i])) { | |
return array(); | |
} | |
if ($i == count($arrays) - 1) { | |
return $arrays[$i]; | |
} | |
// get combinations from subsequent arrays | |
$tmp = combinations($arrays, $i + 1); | |
$result = array(); | |
// concat each array from tmp with each element from $arrays[$i] | |
foreach ($arrays[$i] as $v) { | |
foreach ($tmp as $t) { | |
$result[] = is_array($t) ? | |
array_merge(array($v), $t) : | |
array($v, $t); | |
} | |
} | |
return $result; | |
} | |
//combinations(array $a1, array $a2, ...); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment