PHPで直積計算

  • 5
    いいね
  • 4
    コメント

PHP5.6以降の書き方に変更しました.

<?php

function direct_product(array ...$arrays)
{
    if (!$tops = array_shift($arrays)) {
        return [];
    }
    if (!$arrays) {
        foreach ($tops as $top) {
            $r[] = [$top];
        }
        return $r;
    }
    if (!$nexts = direct_product(...$arrays)) {
        return [];
    }
    foreach ($tops as $top) {
        foreach ($nexts as $next) {
            $r[] = array_merge([$top], $next);
        }
    }
    return $r;
}

var_export(direct_product(['A', 'B', 'C'], ['a'], [1, 2]));
/*
array (
  0 => 
  array (
    0 => 'A',
    1 => 'a',
    2 => 1,
  ),
  1 => 
  array (
    0 => 'A',
    1 => 'a',
    2 => 2,
  ),
  2 => 
  array (
    0 => 'B',
    1 => 'a',
    2 => 1,
  ),
  3 => 
  array (
    0 => 'B',
    1 => 'a',
    2 => 2,
  ),
  4 => 
  array (
    0 => 'C',
    1 => 'a',
    2 => 1,
  ),
  5 => 
  array (
    0 => 'C',
    1 => 'a',
    2 => 2,
  ),
)
*/

var_export(direct_product(['A', 'B', 'C'], [], [1, 2]));
/*
array (
)
*/