PHP二维数组输出的所有组合 [英] PHP 2D Array output all combinations

查看:569
本文介绍了PHP二维数组输出的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题,弯曲我的脑海里,而现在(!感冒并没有帮助),基本上我有一个PHP数组看起来像这样的例子:

I've had this problem bending my mind for a while now (head cold doesn't help either!), basically 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.

推荐答案

这是所谓的笛卡尔积,在阵列上的 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);

这篇关于PHP二维数组输出的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆