Given an associative array, it's possible to determine its cartesian product while preserving its keys and utilizing them within the inner arrays.
We can approach this problem through induction:
For a single array, the cartesian product is a series of arrays with a single key-value pair representing each item in the original array.
Assuming the product of the first N-1 arrays is known, adding the Nth array involves:
For each existing product, append an element with the Nth array's key and the first value of the Nth array.
Repeating these steps ensures that the product of N arrays is achieved.
function cartesian($input) {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">$result = array(); foreach ($input as $key => $values) { if (empty($values)) { continue; } if (empty($result)) { foreach($values as $value) { $result[] = array($key => $value); } } else { $append = array(); 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 = array(</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">'arm' => array('A', 'B', 'C'), 'gender' => array('Female', 'Male'), 'location' => array('Vancouver', 'Calgary'),
);
print_r(cartesian($input));
Array<br>(</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">[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 Calculate the Cartesian Product of PHP Associative Arrays while Preserving Keys?. For more information, please follow other related articles on the PHP Chinese website!