【问题标题】:How to find every possible combination of arrays in PHP如何在 PHP 中找到所有可能的数组组合
【发布时间】:2011-05-31 18:59:17
【问题描述】:
$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...

谢谢

【问题讨论】:

标签: php arrays permutation


【解决方案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

Google 在这方面太棒了...

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

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

【讨论】:

  • 使用递归函数的任何方式?
  • @Oli:我可以在 python 中做到这一点,但我从未使用过 php 中的对象(它作为一种程序语言要好得多)另外值得注意的是,我错过了一行......你需要$v2."-".$v3 的另外一个,所以我想在递归函数中很难做到(因此 pythons 内置了 list.product() 函数)
【解决方案2】:

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

此外,您希望结果元组省略一个或多个数组,为简单起见,我将建模为在每个数组中都有一个 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)

【讨论】:

  • 感谢,这个算法也节省了我从三月开始@AndreKR 的一天:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多