When dealing with multiple arrays, there may arise a need to generate a table containing every possible combination of elements from these arrays, while avoiding repetitions. This mathematical operation is known as the Cartesian product.
To address this challenge in PHP, consider utilizing the following function:
function array_cartesian() { $_ = func_get_args(); if(count($_) == 0) return array(array()); $a = array_shift($_); $c = call_user_func_array(__FUNCTION__, $_); $r = array(); foreach($a as $v) foreach($c as $p) $r[] = array_merge(array($v), $p); return $r; } $cross = array_cartesian( array('apples', 'pears', 'oranges'), array('steve', 'bob') ); print_r($cross);
This function takes variable-length arguments, each representing an array. It recursively calculates the Cartesian product by selecting an element from the first array and combining it with all possible Cartesian products of the remaining arrays.
The result is a nested array containing every unique combination of elements from the input arrays. In the given example, the Cartesian product of two arrays will produce:
Array 0 Array 1 apples steve apples bob pears steve pears bob
This solution is not only effective for arrays with two dimensions but can also be extended to handle any number of arrays. It provides a concise and elegant way to solve the Cartesian product problem in PHP.
The above is the detailed content of How to Calculate the Cartesian Product of Multiple Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!