我整天都在看PHP数组排列/组合问题..仍然不知道:/
如果我有一个像这样的数组:
20 //key being 0 20 //key being 1 22 //key being 2 24 //key being 3
我需要类似的组合:
20, 20, 22 //keys being 0 1 2 20, 20, 24 //keys being 0 1 3 20, 22, 24 //keys being 0 2 3 20, 22, 24 //keys being 1 2 3
我目前拥有的代码给我:
20, 22, 24
因为它不想重复20 …但这就是我所需要的!
这是我的代码。它直接来自Php递归来获取字符串的所有可能性
function getCombinations($base,$n){ $baselen = count($base); if($baselen == 0){ return; } if($n == 1){ $return = array(); foreach($base as $b){ $return[] = array($b); } return $return; }else{ //get one level lower combinations $oneLevelLower = getCombinations($base,$n-1); //for every one level lower combinations add one element to them that the last element of a combination is preceeded by the element which follows it in base array if there is none, does not add $newCombs = array(); foreach($oneLevelLower as $oll){ $lastEl = $oll[$n-2]; $found = false; foreach($base as $key => $b){ if($b == $lastEl){ $found = true; continue; //last element found } if($found == true){ //add to combinations with last element if($key < $baselen){ $tmp = $oll; $newCombination = array_slice($tmp,0); $newCombination[]=$b; $newCombs[] = array_slice($newCombination,0); } } } } } return $newCombs; }
我一直在玩($b == $lastEl)线,没有运气
($b == $lastEl)
===============
我用12个项目的数组尝试了其中的一些算法,最终耗尽了内存。但是,我当前正在使用的算法不会给我带来内存不足的错误……但是……我需要那些重复项!
如果您不介意使用几个全局变量,则可以在PHP中执行此操作):
<?PHP $result = array(); $combination = array(); function combinations(array $myArray, $choose) { global $result, $combination; $n = count($myArray); function inner ($start, $choose_, $arr, $n) { global $result, $combination; if ($choose_ == 0) array_push($result,$combination); else for ($i = $start; $i <= $n - $choose_; ++$i) { array_push($combination, $arr[$i]); inner($i + 1, $choose_ - 1, $arr, $n); array_pop($combination); } } inner(0, $choose, $myArray, $n); return $result; } print_r(combinations(array(20,20,22,24), 3)); ?>
输出:
Array ( [0] => Array ( [0] => 20 [1] => 20 [2] => 22 ) [1] => Array ( [0] => 20 [1] => 20 [2] => 24 ) [2] => Array ( [0] => 20 [1] => 22 [2] => 24 ) [3] => Array ( [0] => 20 [1] => 22 [2] => 24 ) )