20

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
stukerr
  • 716
  • 3
  • 10
  • 18
  • Will there be Array 2, Array 3, Array N? Or only two arrays? – Silver Light Mar 25 '10 at 15:05
  • Hi sorry for not making clearer, there could be array 2, array 3 up to array n. Thanks. – stukerr Mar 25 '10 at 15:05
  • What you need is a cross join done easy in SQL, but needs some thinking in PHP – Silver Light Mar 25 '10 at 15:15
  • As it happens this is coming from a mySQL database, all the options (apples, pears, oranges, steve, bob, etc.) are in one table kit a key to another table defining which group they are in (fruits, people etc.), any ideas how I could work that in mysql ? – stukerr Mar 25 '10 at 15:20

10 Answers10

23

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);
user187291
  • 53,363
  • 19
  • 95
  • 127
  • 1
    If this function lives in a class, you might want to change the user_func call like so: `$c = call_user_func_array(array($this,__FUNCTION__), $_);`. Also, it can give a warning (not an array) if input-arrays aren't of equal size. – Nanne Aug 21 '12 at 14:43
  • This is a good solution but the result of the first short circuit is truthy, which does not make sense to me. Try [this one](http://stackoverflow.com/a/4743758/315024). – Walf Oct 03 '14 at 03:34
4

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

Foo Bah
  • 25,660
  • 5
  • 55
  • 79
3

Syom copied http://www.php.net/manual/en/ref.array.php#54979 but I adapted it this to become an associative version:

function array_cartesian($arrays) {
  $result = array();
  $keys = array_keys($arrays);
  $reverse_keys = array_reverse($keys);
  $size = intval(count($arrays) > 0);
  foreach ($arrays as $array) {
    $size *= count($array);
  }
  for ($i = 0; $i < $size; $i ++) {
    $result[$i] = array();
    foreach ($keys as $j) {
      $result[$i][$j] = current($arrays[$j]);
    }
    foreach ($reverse_keys as $j) {
      if (next($arrays[$j])) {
        break;
      }
      elseif (isset ($arrays[$j])) {
        reset($arrays[$j]);
      }
    }
  }
  return $result;
}
chx
  • 11,270
  • 7
  • 55
  • 129
2

I needed to do the same and I tried the previous solutions posted here but could not make them work. I got a sample from this clever guy http://www.php.net/manual/en/ref.array.php#54979. However, his sample did not managed the concept of no repeating combinations. So I included that part. Here is my modified version, hope it helps:

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

    $res_matrix = $this->array_cartesian_product( $data );

    foreach ( $res_matrix as $res_array )
    {
        foreach ( $res_array as $res )
        {
            echo $res . " - ";
        }
        echo "<br/>";
    }


function array_cartesian_product( $arrays )
{
    $result = array();
    $arrays = array_values( $arrays );

    $sizeIn = sizeof( $arrays );
    $size = $sizeIn > 0 ? 1 : 0;
    foreach ($arrays as $array)
        $size = $size * sizeof( $array );
    $res_index = 0;
    for ( $i = 0; $i < $size; $i++ )
    {
        $is_duplicate = false;
        $curr_values  = array();
        for ( $j = 0; $j < $sizeIn; $j++ )
        {
            $curr = current( $arrays[$j] );
            if ( !in_array( $curr, $curr_values ) )
            {
                array_push( $curr_values , $curr ); 
            }
            else
            {
                $is_duplicate = true;
                break;
            }
        }
        if ( !$is_duplicate )
        {
            $result[ $res_index ] = $curr_values;
            $res_index++;
        }
        for ( $j = ( $sizeIn -1 ); $j >= 0; $j-- )
        {
            $next = next( $arrays[ $j ] );
            if ( $next )
            {
                break;
            }
            elseif ( isset ( $arrays[ $j ] ) )
            {
                reset( $arrays[ $j ] );
            }
        }
    }
    return $result;
}

The result would be something like this:
apples - steve
apples - bob
pears - steve
pears - bob
oranges - steve
oranges - bob

If you the data array is something like this:

  $data = array(
        array('Amazing', 'Wonderful'),
        array('benefit', 'offer', 'reward'),
        array('Amazing', 'Wonderful')
    );

Then it will print something like this:

Amazing - benefit - Wonderful
Amazing - offer - Wonderful
Amazing - reward - Wonderful
Wonderful - benefit - Amazing
Wonderful - offer - Amazing
Wonderful - reward - Amazing

Sergio
  • 310
  • 4
  • 9
1

This works I think - although after writing it I realised it's pretty similar to what others have put, but it does give you an array in the format requested. Sorry for the poor variable naming.

$output = array();
combinations($array, $output);
print_r($output);

function combinations ($array, & $output, $index = 0, $p = array()) {
    foreach ( $array[$index] as $i => $name ) {
        $copy = $p;
        $copy[] = $name;
        $subIndex = $index + 1;
        if (isset( $array[$subIndex])) {
            combinations ($array, $output, $subIndex, $copy);
        } else {
            foreach ($copy as $index => $name) {
                if ( !isset($output[$index])) {
                    $output[$index] = array();   
                }
                $output[$index][] = $name;   
            }
        }
    }
}
user187291
  • 53,363
  • 19
  • 95
  • 127
Tom Haigh
  • 57,217
  • 21
  • 114
  • 142
1

@user187291

I modified this to be

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

so it returns that all-important empty array (the same result as no combinations) when you pass 0 arguments.

Only noticed this because I'm using it like

$combos = call_user_func_array('array_cartesian', $array_of_arrays);
Walf
  • 8,535
  • 2
  • 44
  • 59
1
foreach($parentArray as $value) {
    foreach($subArray as $value2) {
        $comboArray[] = array($value, $value2); 
    }
}

Don't judge me..

Dalton Conley
  • 1,599
  • 2
  • 28
  • 36
0

I had to make combinations from product options. This solution uses recursion and works with 2D array:

function options_combinations($options) {
    $result = array();
    if (count($options) <= 1) {
        $option = array_shift($options);
        foreach ($option as $value) {
            $result[] = array($value);
        }
    } else {
        $option = array_shift($options);
        $next_option = options_combinations($options);
        foreach ($next_option as $next_value) {
            foreach ($option as $value) {
                $result[] = array_merge($next_value, array($value));
            }
        }
    }
    return $result;
}

$options = [[1,2],[3,4,5],[6,7,8,9]];
$c = options_combinations($options);
foreach ($c as $combination) {
    echo implode(' ', $combination)."\n";
}
0

Elegant implementation based on native Python function itertools.product

function direct_product(array ...$arrays)
{
    $result = [[]];
    foreach ($arrays as $array) {
        $tmp = [];
        foreach ($result as $x) {
            foreach ($array as $y) {
                $tmp[] = array_merge($x, [$y]);
            }
        }
        $result = $tmp;
    }
    return $result;
}
mpyw
  • 5,526
  • 4
  • 30
  • 36
0
function array_comb($arrays)
{
    $result = array();
    $arrays = array_values($arrays);
    $sizeIn = sizeof($arrays);
    $size = $sizeIn > 0 ? 1 : 0;
    foreach ($arrays as $array)
        $size = $size * sizeof($array);
    for ($i = 0; $i < $size; $i ++)
    {
        $result[$i] = array();
        for ($j = 0; $j < $sizeIn; $j ++)
            array_push($result[$i], current($arrays[$j]));
        for ($j = ($sizeIn -1); $j >= 0; $j --)
        {
            if (next($arrays[$j]))
                break;
            elseif (isset ($arrays[$j]))
                reset($arrays[$j]);
        }
    }
    return $result;
}
Simon
  • 22,637
  • 36
  • 92
  • 121