Given an associative array with multiple sub-arrays representing different attributes, the task is to compute the Cartesian product while preserving the keys and their corresponding values.
For an array $input with N sub-arrays, where each sub-array has Cn elements, we can proceed with induction:
Assuming we have the Cartesian product of the first N-1 sub-arrays, we can compute the product of the Nth sub-array by:
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));
Will output the desired Cartesian product, preserving the keys and values:
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.
The above is the detailed content of How to Compute the Cartesian Product of PHP Associative Arrays While Preserving Key-Value Pairs?. For more information, please follow other related articles on the PHP Chinese website!