Created
July 19, 2016 07:55
-
-
Save fancyweb/e845834f3e4eedf902d1e9385271f7f9 to your computer and use it in GitHub Desktop.
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 | |
// copyright josé 2002 | |
/** | |
* @param array $array | |
* | |
* @return array | |
*/ | |
public static function cartesianProduct(array $array) | |
{ | |
$count = count($array); | |
if ($count <= 1) { | |
return $count > 0 ? array_map(function ($array) { | |
return array($array); | |
}, $array[0]) : $array; | |
} | |
$cartesianProduct = array(); | |
$last = array_pop($array); | |
foreach ($last as $value) { | |
foreach (self::cartesianProduct($array) as $toAdd) { | |
$cartesianProduct[] = is_array($toAdd) ? array_merge($toAdd, array($value)) : array( | |
$toAdd, | |
$value | |
); | |
} | |
} | |
return $cartesianProduct; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment