生成组合数组PHP

阿库巴巴斯

嗨,大家好,我有一个像这样的数组

$array1 = array('a','b','c','d)

我想与这样的输出结合

  • 'a,b,c'
  • 'a,b,d'
  • 'a,c,d'
  • 'b,c,d'

问题是创建一个具有可变数字而不是多个变量的函数,有人可以帮助我吗?

阿克沙伊

试试看

[akshay@localhost tmp]$ cat permutation_comb.php
<?php

function _perm($comb,$arr)
{

    $arr_len = count($arr);
    $comb = intval($comb);
    if ($comb > $arr_len)
    {
       $p = 0;
    }
 elseif ($arr_len == $comb)
    {
       $p = 1;
    }
   else {
        if ($comb >= $arr_len - $comb)
        {
            $l = $comb+1;
            for ($i = $l+1 ; $i <= $arr_len ; $i++)
                $l *= $i;
                $m  = 1;
            for ($i = 2 ; $i <= $arr_len-$comb ; $i++)
                $m *= $i;
        }
   else {
            $l = ($arr_len-$comb) + 1;
            for ($i = $l+1 ; $i <= $arr_len ; $i++)
                $l *= $i;
                $m  = 1;
            for ($i = 2 ; $i <= $comb ; $i++)
                $m *= $i;           
        }
       }

     if(!isset($p)){ $p = $l/$m ; }

     $out = array_fill(0, $p, array_fill(0, $comb, '') );

     $t = array();
     for ($i = 0 ; $i < $comb ; $i++)
            $t[$i] = $i;

     $out[0] = $t;
     for ($i = 1 ; $i < $p ; $i++)
     {
        if ($t[$comb-1] != count($arr)-1)
        {
            $t[$comb-1]++;
        }
   else {
            $xx = -1;
            for ($j = $comb-2 ; $j >= 0 ; $j--)
            if ($t[$j]+1 != $t[$j+1])
                {
                    $xx = $j;
                    break;
                }

            if ($xx == -1)
                break;

            $t[$xx]++;
            for ($j = $xx+1 ; $j < $comb ; $j++)   
                $t[$j] = $t[$xx]+$j-$xx;
        }
        $out[$i] = $t;
    }
    for ($i = 0 ; $i < $p ; $i++)
        for ($j = 0 ; $j < $comb ; $j++)
            $out[$i][$j] = $arr[$out[$i][$j]];  
    return $out;
}

    $Input  =   array('a','b','c','d');
    $output =   array_map(function($a){ return implode(",",$a); },_perm(3, $Input));


   // Input
   print_r($Input);

   // Combination output
   print_r($output);
?> 

输出

[akshay@localhost tmp]$ php permutation_comb.php
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
Array
(
    [0] => a,b,c
    [1] => a,b,d
    [2] => a,c,d
    [3] => b,c,d
)

要获取所有可能的字符组合,请修改函数的调用部分,如下所示

$output =   array();    
for($i=1; $i<=count($Input); $i++)
{
  $output =  array_merge($output,  array_map(function($a){ return implode(",",$a); },_perm($i, $Input)) ) ;
} 

哪个结果

[akshay@localhost tmp]$ php permutation_comb.php
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => a,b
    [5] => a,c
    [6] => a,d
    [7] => b,c
    [8] => b,d
    [9] => c,d
    [10] => a,b,c
    [11] => a,b,d
    [12] => a,c,d
    [13] => b,c,d
    [14] => a,b,c,d
)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章