如何在PHP中找到每个可能的数组组合

时间:2010-12-28 21:50:45

标签: php arrays permutation

$data = array(
'a' => array('a1', 'a2', 'a3'),
'b' => array('b1', 'b2', 'b3', 'b4'),
'c' => array('c1', 'c2', 'c3', 'c4', 'c5'));

获取

a1
a2
a3
b1
b2
b3
b4
c1
c2
c3
c4
c5

a1 b1
a1 b2
a1 b3
a1 b4
a1 c1
a1 c2
a1 c3
a1 c4
a1 c5

b1 c1
b1 c2
b1 c3
b1 c4
b1 c5
b2 c1
b2 c2
b2 c3
b2 c4
b2 c5
b3 c1
b3 c2
b3 c3
b3 c4
b3 c5
b4 c1
b4 c2
b4 c3
b4 c4
b4 c5

a1 b1 c1
a1 b1 c2
a1 b1 c3
a1 b1 c4
a1 b1 c5
a1 b2 c1
a1 b2 c2
a1 b2 c3
a1 b2 c4
a1 b2 c5
a1 b3 c1
a1 b3 c2
a1 b3 c3
a1 b3 c4
a1 b3 c5
a1 b4 c1
a1 b4 c2
a1 b4 c3
a1 b4 c4
a1 b4 c5
etc...

由于

2 个答案:

答案 0 :(得分:5)

显然你想构建几个数组的笛卡尔积,即每个元素与其他元素相结合。

此外,您希望结果元组省略一个或多个这些数组,为简单起见,我将建模为每个数组中都有null元素:

$result = array(array()); // We need to start with one element already, because thats the identity element of the cartesian product
foreach ($data as $arr)
{
    array_push($arr,null); // Add a null element to the array to get tuples with less than all arrays

    // This is the cartesian product:
    $new_result = array();
    foreach ($result as $old_element)
        foreach ($arr as $el)
            $new_result []= array_merge($old_element,array($el));
    $result = $new_result;
}

请注意,对于结果行a1 b3 c2,此代码会为您提供array('a1','b3','c2'),而结果行b4 c3会为您提供array('b4','c3',null)

答案 1 :(得分:1)

如果你想全部打印出来,只需使用循环:

foreach($data['a'] as $k1 =>$v1){
    $output[]=$v1;
    foreach($data['b'] as $k2 => $v2){
        $output[]=$v2;
        $output[]=$v1."-".$v2;
        foreach($data['c'] as $k3 => $v3){
            $output[]=$v3;
            $output[]=$v1."-".$v2."-".$v3;
        }
    }
} 

http://www.webdeveloper.com/forum/showthread.php?t=168409

谷歌很棒......

如果你想看看有多少种可能性,请将它们相乘:

$count1=1;
$count2=1;
for each $data as $item{
$count2*=count($item);
}