給定一個具有多個代表不同屬性的子數組的關聯數組,任務是計算笛卡爾積,同時保留密鑰及其對應的
對於有N 個子數組的數組$input,其中每個子數組有Cn 個元素,我們可以繼續歸納:
假設我們有前N-1 個子數組的笛卡爾積,我們可以用以下方式計算第 N個子數組的乘積:
function cartesian($input) { $result = []; while (list($key, $values) = each($input)) { if (empty($values)) { continue; } if (empty($result)) { foreach ($values as $value) { $result[] = [$key => $value]; } } else { $append = []; foreach ($result as &$product) { $product[$key] = array_shift($values); $copy = $product; foreach ($values as $item) { $copy[$key] = $item; $append[] = $copy; } array_unshift($values, $product[$key]); } $result = array_merge($result, $append); } } return $result; }
$input = [ 'arm' => ['A', 'B', 'C'], 'gender' => ['Female', 'Male'], 'location' => ['Vancouver', 'Calgary'], ]; print_r(cartesian($input));
Array ( [0] => Array ( [arm] => A [gender] => Female [location] => Vancouver ) [1] => Array ( [arm] => A [gender] => Female [location] => Calgary ) [2] => Array ( [arm] => A [gender] => Male [location] => Vancouver ) ...etc.
以上是如何在保留鍵值對的同時計算 PHP 關聯數組的笛卡爾積?的詳細內容。更多資訊請關注PHP中文網其他相關文章!