Skip to content

Instantly share code, notes, and snippets.

@mig1098
Forked from jwage/Cartesian.php
Last active August 26, 2015 14:14
Show Gist options
  • Save mig1098/bfbd05820d0206909741 to your computer and use it in GitHub Desktop.
Save mig1098/bfbd05820d0206909741 to your computer and use it in GitHub Desktop.
PHP Cartesian Function
<?php
$attributeValues = array(
'color' => array('Red', 'White', 'Blue'),
'size' => array(1, 2, 3, 4),
'fabric' => array('Cloth', 'Silk')
);
class Cartesian
{
public static function build($set)
{
if (!$set) {
return array(array());
}
$subset = array_shift($set);
$cartesianSubset = self::build($set);
$result = array();
foreach ($subset as $value) {
foreach ($cartesianSubset as $p) {
array_unshift($p, $value);
$result[] = $p;
}
}
return $result;
}
}
print_r(Cartesian::build($attributeValues));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment