Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cartesian Product of N arrays

Tags:

I have a PHP array which looks like this example:

$array[0][0] = 'apples';
$array[0][1] = 'pears';
$array[0][2] = 'oranges';

$array[1][0] = 'steve';
$array[1][1] = 'bob';

And I would like to be able to produce from this a table with every possible combination of these, but without repeating any combinations (regardless of their position), so for example this would output

Array 0            Array 1
apples             steve
apples             bob
pears              steve
pears              bob

But I would like for this to be able to work with as many different arrays as possible.

like image 771
stukerr Avatar asked Mar 25 '10 15:03

stukerr


People also ask

How do you find the Cartesian product?

In mathematics, the Cartesian Product of sets A and B is defined as the set of all ordered pairs (x, y) such that x belongs to A and y belongs to B. For example, if A = {1, 2} and B = {3, 4, 5}, then the Cartesian Product of A and B is {(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)}.

What is the Cartesian product of a set with itself?

If X=Y, we can denote the Cartesian product of X with itself as X×X=X2. For examples, since we can represent both the x-axis and the y-axis as the set of real numbers R, we can write the xy-plane as R×R=R2.

How many elements are in a Cartesian product?

A deck of cards The Cartesian product of these sets returns a 52-element set consisting of 52 ordered pairs, which correspond to all 52 possible playing cards.

Is Cartesian product the same as cross product?

It's just the same symbol, and definitely not the same thing: the Cartesian product is a set (of vectors), the cross product is a vector.


2 Answers

this is called "cartesian product", php man page on arrays http://php.net/manual/en/ref.array.php shows some implementations (in comments).

and here's yet another one:

function array_cartesian() {
    $_ = func_get_args();
    if(count($_) == 0)
        return array(array());
    $a = array_shift($_);
    $c = call_user_func_array(__FUNCTION__, $_);
    $r = array();
    foreach($a as $v)
        foreach($c as $p)
            $r[] = array_merge(array($v), $p);
    return $r;
}

$cross = array_cartesian(
    array('apples', 'pears',  'oranges'),
    array('steve', 'bob')
);

print_r($cross);
like image 166
user187291 Avatar answered Oct 09 '22 15:10

user187291


You are looking for the cartesian product of the arrays, and there's an example on the php arrays site: http://php.net/manual/en/ref.array.php

like image 43
Foo Bah Avatar answered Oct 09 '22 17:10

Foo Bah