I have this array and I use it as INPUT:
Array
(
[0] => Array
(
[11134] => 3.430
[11131] => 2.720
[11128] => 1.077
)
[1] => Array
(
[11135] => 2.381
[11132] => 2.636
[11129] => 2.920
)
[2] => Array
(
[11136] => 1.220
[11133] => 2.550
[11130] => 3.895
)
)
I need to print the cartesian product of this array. I used the answer located here, but it doesn't really help me at all. I have modified the function Jon posted to make it faster (really just switched array_shift
for array_pop
so it wouldn't reindex the array as numeric):
function cartesian($input) {
$result = array();
while (list($key, $values) = each($input)) {
if (empty($values)) {
continue;
}
if (empty($result)) {
foreach($values as $value) {
$result[] = array($key => $value);
}
}
else {
$append = array();
foreach($result as &$product) {
$product[$key] = array_pop($values);
$copy = $product;
foreach($values as $item) {
$copy[$key] = $item;
$append[] = $copy;
}
$values[] = $product[$key];
}
$result = array_merge($result, $append);
}
}
return $result;
}
The answer given prints the following array:
Array
(
[0] => Array
(
[0] => 3.430
[1] => 2.920
[2] => 3.895
)
[1] => Array
(
[0] => 2.720
[1] => 2.920
[2] => 3.895
)
...
)
which is not what I exactly want. THE DESIRED OUTPUT of the function is:
Array
(
[0] => Array
(
[11134] => 3.430
[11129] => 2.920
[11130] => 3.895
)
[1] => Array
(
[11131] => 2.720
[11129] => 2.920
[11130] => 3.895
)
...
)
I came up with how to make the first element of my new array to look like I need, the part of the code looks like this:
if (empty($result)) {
foreach($values as $key => $value) {
$result[] = array($key => $value);
}
}
But that's where I'm stuck. I can't get the other values to grab their keys and display as the keys. The final array I managed to get looks like this.
Array
(
[0] => Array
(
[11134] => 3.430
[1] => 2.920
[2] => 3.895
)
[1] => Array
(
[11131] => 2.720
[1] => 2.920
[2] => 3.895
)
...
)
I think I got it, I googled "PHP combinations" (Assuming that a combination is similar to a Cartesian product, I think it is :s) and used this code as a base. The change I needed to make was instead of merging the arrays I had to use a union because according to the php manual:
and
CODE:
RESULTS: