Creating Cartesian Products of Multiple Arrays in PHP
Consider a PHP array structure like the following:
$array[0][0] = 'apples'; $array[0][1] = 'pears'; $array[0][2] = 'oranges'; $array[1][0] = 'steve'; $array[1][1] = 'bob';
Objective: To generate a tabulated list of all possible combinations of elements from these arrays, without duplication.
Solution:
The concept of generating all possible combinations from multiple arrays is known as the "Cartesian product." There are several methods to achieve this in PHP.
One approach is to utilize PHP's array functions. The following code snippet implements the Cartesian product using func_get_args() and recursion:
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; }
To use this function, pass an arbitrary number of arrays as arguments. For example, to generate the Cartesian product of the above arrays:
$cross = array_cartesian( array('apples', 'pears', 'oranges'), array('steve', 'bob') );
The result, stored in $cross, will be an array containing all possible combinations:
print_r($cross);
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 ) )
以上是如何在 PHP 中產生多個數組的笛卡爾積?的詳細內容。更多資訊請關注PHP中文網其他相關文章!