dongshou2024 2015-05-28 09:33
浏览 5
已采纳

PHP可能有限的数组组合[关闭]

Here i have used following function to get the possible combinations for the given array.

    function combination($array, $str = '') 
{
   $current = array_shift($array);
   if(count($array) > 0) {
       foreach($current as $element) 
       {

           combination($array, $str.$element);

       }
   }
   else
   {
       foreach($current as $element) 
       {
         echo '<br>'.$str.$element;

       }
   } 
}

$array = array(
                array( ' A1', ' A2', ' A3', ' A4'),
                array(' B1', ' B2', ' B3', ' B4'),
                array(' C1',' C2'));



combination($array);    

    OUTPUT:
A1 B1 C1
A1 B1 C2
A1 B2 C1
A1 B2 C2
A1 B3 C1
A1 B3 C2
A1 B4 C1
A1 B4 C2
A2 B1 C1
A2 B1 C2
A2 B2 C1
A2 B2 C2
A2 B3 C1
A2 B3 C2
A2 B4 C1
A2 B4 C2
A3 B1 C1
A3 B1 C2
A3 B2 C1


EXPECTED: In this i want only to display first 10 combinations.

Here i am getting the all possible combinations of given array. But i want to display only the first 10 combinations of possible array. Please help me to overcome the issue.

  • 写回答

1条回答 默认 最新

  • donglengyuan6826 2015-05-28 11:13
    关注

    This is the best and optimal solution for you. try it:-

    <?php
    global $i;
    $i = 1; // define a global variable with value 1
    function combination($array, $str = '') 
    {
      global $i;
      $current = array_shift($array);
       if(count($array) > 0 && $i <=10) { // check that value is less or equal to 10 if yes then execute otherwise exit
    
           foreach($current as $element) 
           { 
               combination($array, $str.$element);
           }
       }
       if(count($array) <= 0 && $i <=10){ //again check if value is less or equal to 10 then execute otherwise exit 
    
           foreach($current as $element) 
           {        
                echo '<br>'.$str.$element;
                $i++; // increase the  value of global variable while iteration.
           }
    
       }
    }
    
    
    $array = array(array(' A1', ' A2', ' A3', ' A4'),array(' B1', ' B2', ' B3', ' B4'),array(' C1',' C2'));
    combination($array);
    ?>
    

    Output:- http://prntscr.com/7abrrx

    Note:- Please check and tell works or not?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝