Cartesian Product of N arrays Cartesian Product of N arrays arrays arrays

Cartesian Product of N arrays


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);


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


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;}