Home  >  Article  >  Backend Development  >  Detailed explanation of PHP implementation of Cartesian product operation of arrays

Detailed explanation of PHP implementation of Cartesian product operation of arrays

小云云
小云云Original
2017-12-18 10:15:012224browse

This article mainly introduces the implementation of the Cartesian product operation of arrays in PHP, and analyzes the related implementation and usage techniques of the Cartesian product operation of PHP arrays in the form of examples. Friends who need it can refer to it. I hope it can help everyone.

The Cartesian product of arrays is quite useful in practice. For example, it is often used when calculating product specifications. Here 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 above 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 string form, 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
)

Related recommendations:

How to generate Cartesian product by php custom function

PHP custom function generates Cartesian product

Find the Cartesian product of multiple arrays

The above is the detailed content of Detailed explanation of PHP implementation of Cartesian product operation of arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn