An Example of Cartesian Product Operation of Array Realized by PHP

  • 2021-08-28 19:38:13
  • OfStack

In this paper, an example is given to describe the Cartesian product operation of arrays realized by PHP. Share it for your reference, as follows:

Array of Cartesian product in practice or quite useful, such as the calculation of commodity specifications are often used, the following write a way to achieve, 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 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 want 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 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
)

More readers interested in PHP can check the topic of this site: "PHP Mathematical Operation Skills Summary", "PHP Operation and Operator Usage Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Encyclopedia", "PHP Common Traversal Algorithms and Skills Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php Regular Expression Usage Summary" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: