【问题标题】:PHP possible limited combinations of array [closed]PHP可能有限的数组组合[关闭]
【发布时间】:2015-05-28 09:33:38
【问题描述】:

这里我使用了以下函数来获取给定数组的可能组合。

    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.

在这里,我得到了给定数组的所有可能组合。但我只想显示可能数组的前 10 个组合。请帮我解决这个问题。

【问题讨论】:

  • 预期输出是什么?
  • 好的,我将添加我的代码
  • 请你们帮我提供一个解决方案
  • 请您回复并提出一些解决方案。如果可能的话,再过 1 小时,因为我必须在今天完成任务
  • 非常感谢您的解决方案。它工作正常。

标签: php arrays


【解决方案1】:

这是最适合您的最佳解决方案。试试看:-

<?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);
?>

输出:- http://prntscr.com/7abrrx

注意:- 请检查并告诉作品与否?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多