note 46497 deleted from ref.array by tularis
| From: | tularis@php.net | Date: | Sun, 26 Aug 2007 16:38:37 +0000 |
| Subject: | note 46497 deleted from ref.array by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-129810@lists.php.net to get a copy of this message | ||
Note Submitter: skopek at mediatac dot com
----
I needed a function, that returns the cartesian product of some input-arrays in an array. Here is
the function that can do that:
<?php
function array_cartesian_product($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_product($arrays));
?>
The output is:
Array
(
[0] => Array
(
[0] => a
[1] => x
)
[1] => Array
(
[0] => a
[1] => y
)
[2] => Array
(
[0] => a
[1] => z
)
[3] => Array
(
[0] => b
[1] => x
)
[4] => Array
(
[0] => b
[1] => y
)
[5] => Array
(
[0] => b
[1] => z
)
)
Greets
Jan