N个数组的笛卡尔积 [英] Cartesian Product of N arrays
本文介绍了N个数组的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 PHP 数组,它看起来像这个例子:
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.
推荐答案
这被称为笛卡尔积",数组上的 php 手册页 http://php.net/manual/en/ref.array.php 显示了一些实现(在评论中).
this is called "cartesian product", php man page on arrays http://php.net/manual/en/ref.array.php shows some implementations (in comments).
这里还有一个:
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);
这篇关于N个数组的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文