Last active
August 29, 2015 14:27
-
-
Save Mulkave/e835f10e542d4b554b57 to your computer and use it in GitHub Desktop.
Find all the possible combinations of the given associative array(s)
This file contains hidden or 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 | |
// http://stackoverflow.com/a/8567199/1542779 | |
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; | |
} | |
// http://stackoverflow.com/a/8567479/1542779 | |
function array_cartesian_product($arrays) | |
{ | |
$result = array(); | |
$arrays = array_values($arrays); | |
$sizeIn = sizeof($arrays); | |
$size = $sizeIn > 0 ? 1 : 0; | |
foreach ($arrays as $array) | |
$size = $size * sizeof($array); | |
for ($i = 0; $i < $size; $i ++) | |
{ | |
$result[$i] = array(); | |
for ($j = 0; $j < $sizeIn; $j ++) | |
array_push($result[$i], current($arrays[$j])); | |
for ($j = ($sizeIn -1); $j >= 0; $j --) | |
{ | |
if (next($arrays[$j])) | |
break; | |
elseif (isset ($arrays[$j])) | |
reset($arrays[$j]); | |
} | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment