PHP implements the Cartesian Product Operation for arrays.
This example describes how PHP implements the Cartesian Product Operation for arrays. We will share this with you for your reference. The details are as follows:
The Cartesian product of the array is quite useful in practice. For example, it is often used to calculate the Product Specification. Below is an implementation method, as shown in the following code:
$arr = array( array(2), array(6,7), array('a','b','c'));function dikaer($arr){ $arr1 = array(); $result = array_shift($arr); while($arr2 = array_shift($arr)){ $arr1 = $result; $result = array(); foreach($arr1 as $v){ foreach($arr2 as $v2){ if(!is_array($v))$v = array($v); if(!is_array($v2))$v2 = array($v2); $result[] = array_merge_recursive($v,$v2); } } } return $result;}
The output result of the preceding example is as follows:
Array( [0] => Array ( [0] => 2 [1] => 6 [2] => a ) [1] => Array ( [0] => 2 [1] => 6 [2] => b ) [2] => Array ( [0] => 2 [1] => 6 [2] => c ) [3] => Array ( [0] => 2 [1] => 7 [2] => a ) [4] => Array ( [0] => 2 [1] => 7 [2] => b ) [5] => Array ( [0] => 2 [1] => 7 [2] => c ))
If you need to output the result in the string format, you can change the code to this
function dikaer($arr){ $arr1 = array(); $result = array_shift($arr); while($arr2 = array_shift($arr)){ $arr1 = $result; $result = array(); foreach($arr1 as $v){ foreach($arr2 as $v2){ $result[] = $v.','.$v2; } } } return $result;}
The output result is as follows:
Array( [0] => 2,6,a [1] => 2,6,b [2] => 2,6,c [3] => 2,7,a [4] => 2,7,b [5] => 2,7,c)