Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rxnlabs/88c67bbcfbbb6a1544f7 to your computer and use it in GitHub Desktop.
Save rxnlabs/88c67bbcfbbb6a1544f7 to your computer and use it in GitHub Desktop.
PHP - Generate all possible combinations from multidimensional array
// http://www.devnetwork.net/viewtopic.php?f=1&t=133156
function array_cartesian_utm($arrays){
//returned array...
$cartesic = array();
//calculate expected size of cartesian array...
$size=(sizeof($arrays)>0)?1:0;
foreach($arrays as $array){
$size= $size*sizeof($array);
}
for($i=0; $i<$size;$i++) {
$cartesic[$i] = array();
foreach($arrays as $key=>$value){
//die(var_dump($arrays[$j]));
$current = current($arrays[$key]);
//array_push($cartesic[$i], $current);
$cartesic[$i][$key] = $current;
}
//set cursor on next element in the arrays, beginning with the last array
$arrays = array_reverse($arrays);
foreach($arrays as $key=>$value){
//if next returns true, then break
if(next($arrays[$key])) {
break;
} else { //if next returns false, then reset and go on with previuos array...
reset($arrays[$key]);
}
}
}
return $cartesic;
}
// example
$arrays['utm1'] = array("a", "b");
$arrays['utm2'] = array("x", "y", "z");
print_r(array_cartesian_utm($arrays));
// http://www.devnetwork.net/viewtopic.php?f=1&t=133156
function array_cartesian_utm($arrays) {
//returned array...
$cartesic = array();
//calculate expected size of cartesian array...
$size=(sizeof($arrays)>0)?1:0;
foreach($arrays as $array)
{
$size= $size*sizeof($array);
}
for($i=0; $i<$size;$i++) {
$cartesic[$i] = array();
for($j=0;$j<sizeof($arrays);$j++)
{
$current = current($arrays[$j]);
array_push($cartesic[$i], $current);
}
//set cursor on next element in the arrays, beginning with the last array
for($j=(sizeof($arrays)-1);$j>=0;$j--)
{
//if next returns true, then break
if(next($arrays[$j])) {
break;
} else { //if next returns false, then reset and go on with previuos array...
reset($arrays[$j]);
}
}
}
return $cartesic;
}
// example
$arrays[0] = array("a", "b");
$arrays[1] = array("x", "y", "z");
print_r(array_cartesian_utm($arrays));
@Titum
Copy link

Titum commented Dec 21, 2017

For the associative function :
To preserve the keys for numeric keys you need to change the ligne 23: $arrays = array_reverse($arrays,true);

But that doesn't works :(
The result is:
Array ( [0] => Array ( [utm1] => a [utm2] => x ) [1] => Array ( [utm2] => y [utm1] => a ) [2] => Array ( [utm1] => b [utm2] => y ) [3] => Array ( [utm2] => z [utm1] => b ) [4] => Array ( [utm1] => a [utm2] => x ) [5] => Array ( [utm2] => y [utm1] => a ) )
Combinations are: ax, ay, by, bz, ax, ay
Instead of: ax, ay, az, bx, by, bz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment