Home  >  Article  >  Backend Development  >  How to implement Cartesian product of arrays in php

How to implement Cartesian product of arrays in php

藏色散人
藏色散人Original
2021-12-07 09:20:082125browse

php method to implement the Cartesian product of an array: 1. Create a PHP sample file; 2. Define an array; 3. Implement the Cartesian product of the array through "function dikaer($arr){...}" Calculation is sufficient.

How to implement Cartesian product of arrays in php

#The operating environment of this article: Windows 7 system, PHP version 7.4, Dell G3 computer.

How does PHP implement the Cartesian product of an array?

PHP implements the Cartesian product operation example of an array

The Cartesian product of an array in practice It is quite useful. For example, it is often used when calculating product specifications. Here is an implementation method, as follows:

$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 results of the above example are 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 can be changed to the code like 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
)

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to implement Cartesian product of arrays in php. 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