2014-04-28 193 views
0

我想以更靈活的方式放置這段代碼,以便無論$ sets數組的大小如何都可以工作。我想這可以通過遞歸完成,但無法找到正確的PHP語法。Foreach循環+遞歸

$sets = array(
       array(0, 1, 2, 3), 
       array(0, 1, 2, 3), 
       array(0, 1, 2, 3), 
       array(0, 1, 2, 3) 
       ); 

$combinations = array(); 

foreach($sets[0] as $s1) 
    foreach($sets[1] as $s2) 
     foreach($sets[2] as $s3) 
      foreach($sets[3] as $s4) 
       $combinations[] = array($s1, $s2, $s3, $s4); 

print_r($combinations); 

回答

0

你可以像這樣在遞歸中做到這一點。輸出與您的環路相同

<?php 
$sets = array(
    array(0, 1, 2, 3), 
    array(0, 1, 2, 3), 
    array(0, 1, 2, 3), 
    array(0, 1, 2, 3) 
); 

function get_combinations($sets, &$combinations = array(), &$row = array()) { 
    if (count($sets) == 0) { 
     $combinations[] = $row; 
     return $combinations; 
    } 
    foreach ($sets[0] as $s) { 
     $row[] = $s; 
     get_combinations(array_slice($sets, 1), $combinations, $row); 
     array_pop($row); 
    } 
    return $combinations; 
} 

$combinations = get_combinations($sets); 

print_r($combinations);