Skip to content

Instantly share code, notes, and snippets.

@ItsMeThom-zz
Created July 7, 2017 10:30
Show Gist options
  • Select an option

  • Save ItsMeThom-zz/2312bc0421f193c7c6b22bb9b87eb7dc to your computer and use it in GitHub Desktop.

Select an option

Save ItsMeThom-zz/2312bc0421f193c7c6b22bb9b87eb7dc to your computer and use it in GitHub Desktop.
Cartesian in PHP
function cartesian($input) {
//get cartesian product (permutations) of a nested array
/* x = [
* a = [1,2],
* b = [10,20,30]
* ]
* returns [ [1,10] , [1,20] , [1,30] , [2,10], [2,20], [2,30] ]
*/
$result = array(array());
foreach ($input as $k => $v) {
$permut = array();
foreach($result as $product){
foreach($v as $item) {
$product[$k] = $item;
$permut[] = $product;
}
}
$result = $permut;
}
return $result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment