Generating the Cartesian Product of Multiple Arrays in PHP
Introduction:
Producing combinations from multiple arrays is a common task in programming. The Cartesian product of these arrays is a list of all possible combinations of elements from the input arrays.
Problem:
Given an array with multiple subarrays, we want to generate a table containing all unique combinations of elements from those subarrays. For instance, if we have two subarrays:
$array[0][0] = 'apples'; $array[0][1] = 'pears'; $array[0][2] = 'oranges'; $array[1][0] = 'steve'; $array[1][1] = 'bob';
We expect the output to be:
Array 0 Array 1 apples steve apples bob pears steve pears bob
Solution: Cartesian Product
This problem requires calculating the Cartesian product, which generates all possible combinations of elements from multiple arrays.
Implementation:
One approach to calculate the Cartesian product involves using a recursive function. Here's an example implementation:
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; }
This function takes multiple arrays as inputs. It iterates through the first array and combines each of its elements with all possible combinations of the remaining arrays. The result is a list of all unique combinations.
Example:
Let's apply the solution to our example:
$cross = array_cartesian( array('apples', 'pears', 'oranges'), array('steve', 'bob') ); print_r($cross);
This will output:
Array ( [0] => Array ( [0] => apples [1] => steve ) [1] => Array ( [0] => apples [1] => bob ) [2] => Array ( [0] => pears [1] => steve ) [3] => Array ( [0] => pears [1] => bob ) )
Which matches our expected output.
The above is the detailed content of How to Generate the Cartesian Product of Multiple Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!