PHP 多個一維數組排列組合的所有可能


<?php
    // auth bin.chen 525945448


    $a = array('A');
    $b = array('C');
    $c = array('E');
    $f = array('P');
    $d = array($a,$b,$c,$f );
    //計算每一個數組的長度
    $len = 1;
    $arrLen = count($d); //需要排列數組有多少個
    $recIndex = null; //記錄當前該取的位置
    //foreach 計數 
    $count_3 = 0;
    foreach ($d as $key => $value) {
        $lenRec[$count_3] = count($value);
        $len = $lenRec[$count_3]*$len;
        $recIndex[] = 0;//第一次全部取第0個
        $count_3++;
    }
    //算出% 的值
    $count = 1;
    foreach ($lenRec as $key => $value) {
        $moduloVal = 1;
        
        if($arrLen == $count){
                $modulo[] = count($d[$arrLen-1]); //等於最后一個的長度
        }else{
            $count_1 = 1;
            foreach ($lenRec as $index => $item) {
                $count_1 > $count && $moduloVal = $moduloVal*$item;
                $count_1 ++;
            }
            $modulo[] = $moduloVal;
        }
        $count ++;//為了防止$d key是有值的 不是自然序列 需要計數
    }
    $i = 1;

    while ( $i <= $len) {
        $html = '';
        $count_2 = 0;// 取模
        $temp = '';
        foreach ($d as $value) {
               $html .= $value[$recIndex[$count_2]%$lenRec[$count_2]];
               $count_2 ++;
        }

        echo $html."<br>";
        foreach ($modulo as $key => $value) {
            if($i%$value == 0 && $key < $arrLen - 1 ){
                $recIndex[$key] = $recIndex[$key] +1;   
            } 
            if($key == $arrLen - 1){
                 if($i%$value == 0){
                        $recIndex[$key] = 0;  
                 }else{
                    $recIndex[$key] = $recIndex[$key] +1;  
                 }
            } 
        }
        $i ++;
        //改變獲取的位置
    }

?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM