$arr = array( array('a','b','c'), array('c','f'), array('g','z'), array('x','y'));//$arr子集元素長度可能會多一些//將$arr的子集元素與$arr其他子集元素兩兩組合或者三三四四組合//子集array('a','b','c')中的元素不需要組合//兩兩組合$newarr = array( array('a','c'), array('a','f'), array('b','c'), array('b','f'), array('c','c'), array('c','f'), ……)//三三組合$newarr = array( array('a','c','g'), array('a','f','g'), array('b','c','g'), array('b','f','g'), array('c','c','g'), array('c','f','g'), ……)//四四組合$newarr = array( array('a','c','g','x'), array('a','f','g','x'), array('b','c','g','x'), array('b','f','g','x'), array('c','c','g','x'), array('c','f','g','x'), ……)
用一個函數可以實現嗎?
//$arr:原始數組,$cNum:組合長度function getCombination($arr,$cNum){ ……}
回複內容:
$arr = array( array('a','b','c'), array('c','f'), array('g','z'), array('x','y'));//$arr子集元素長度可能會多一些//將$arr的子集元素與$arr其他子集元素兩兩組合或者三三四四組合//子集array('a','b','c')中的元素不需要組合//兩兩組合$newarr = array( array('a','c'), array('a','f'), array('b','c'), array('b','f'), array('c','c'), array('c','f'), ……)//三三組合$newarr = array( array('a','c','g'), array('a','f','g'), array('b','c','g'), array('b','f','g'), array('c','c','g'), array('c','f','g'), ……)//四四組合$newarr = array( array('a','c','g','x'), array('a','f','g','x'), array('b','c','g','x'), array('b','f','g','x'), array('c','c','g','x'), array('c','f','g','x'), ……)
用一個函數可以實現嗎?
//$arr:原始數組,$cNum:組合長度function getCombination($arr,$cNum){ ……}
遞迴?
$arr = array( array('a', 'b', 'c'), array('c', 'f'), array('g', 'z'), array('x', 'y'));//$arr:原始數組,$cNum:組合長度function getCombination($arr, $cNum) { if ($cNum === 0) { return return array( array('a'), array('b'), array('c'), ); } else { $tmpArr2 = $arr; $resultArr = array(); array_pop($tmpArr2); $lastNewArr = getCombination($tmpArr2, $cNum - 1); for ($i = 0; $i < count($lastNewArr); $i++) { for ($j = 0; $j < count($arr[$cNum]); $j++) { $tmpArr = $lastNewArr[$i]; $tmpArr[] = $arr[$cNum][$j]; $resultArr[] = $tmpArr; } } return $resultArr; }}print_r(getCombination($arr, count($arr) - 1));
呃……我目前的想法是先取符合組合長度規定的數組,再求笛卡爾積,最後合并成新數組……
三個函數完成。
題主的問題應該是 PHP計算二維數組笛卡爾積
吧?如果是的話,請看以下代碼:
class Descartes{ public $sourceArray; public $resultArray; public function __construct($array, $result) { $this->sourceArray = $array; $this->resultArray = $result; } public function calcDescartes($arrIndex, $arrResult) { if ($arrIndex >= count($this->sourceArray)) { array_push($this->resultArray, $arrResult); return ; } $currentArray = $this->sourceArray[$arrIndex]; $currentArrayCount = count($currentArray); $arrResultCount = count($arrResult); for ($i = 0; $i < $currentArrayCount; ++$i) { $currentArraySlice = array_slice($arrResult, 0, $arrResultCount); array_push($currentArraySlice, $currentArray[$i]); $this->calcDescartes($arrIndex + 1, $currentArraySlice); } }}$example = [ ['a', 'b', 'c'], ['c', 'f'], ['g', 'z'], ['x', 'y']];$result = [];$descartes = new Descartes($example, $result);$descartes->calcDescartes(0, $result);var_dump($descartes->resultArray);