首页 > 开发 > PHP > 正文

PHP笛卡尔积实现算法示例

2024-05-04 22:42:36
字体:
来源:转载
供稿:网友

本文实例讲述了PHP笛卡尔积实现算法。分享给大家供大家参考,具体如下:

<?php$arr = array(array(1,3,4,5),array(3,5,7,9),array(76,6,1,0));/**** 实现二维数组的笛卡尔积组合** $arr 要进行笛卡尔积的二维数组** $str 最终实现的笛卡尔积组合,可不写** @return array**/function cartesian($arr,$str = array()){  //去除第一个元素  $first = array_shift($arr);  //判断是否是第一次进行拼接  if(count($str) > 1) {    foreach ($str as $k => $val) {      foreach ($first as $key => $value) {        //最终实现的格式 1,3,76        //可根据具体需求进行变更        $str2[] = $val.','.$value;      }    }  }else{    foreach ($first as $key => $value) {      //最终实现的格式 1,3,76      //可根据具体需求进行变更      $str2[] = $value;    }  }  //递归进行拼接  if(count($arr) > 0){    $str2 = cartesian($arr,$str2);  }  //返回最终笛卡尔积  return $str2;}$cartesian_product = cartesian($arr);print_r($cartesian_product);?>

最终输出格式

Array
(
    [0] => 1,3,76
    [1] => 1,3,6
    [2] => 1,3,1
    [3] => 1,3,0
    [4] => 1,5,76
    [5] => 1,5,6
    [6] => 1,5,1
    [7] => 1,5,0
    [8] => 1,7,76
    [9] => 1,7,6
    [10] => 1,7,1
    [11] => 1,7,0
    [12] => 1,9,76
    [13] => 1,9,6
    [14] => 1,9,1
    [15] => 1,9,0
    [16] => 3,3,76
    [17] => 3,3,6
    [18] => 3,3,1
    [19] => 3,3,0
    [20] => 3,5,76
    [21] => 3,5,6
    [22] => 3,5,1
    [23] => 3,5,0
    [24] => 3,7,76
    [25] => 3,7,6
    [26] => 3,7,1
    [27] => 3,7,0
    [28] => 3,9,76
    [29] => 3,9,6
    [30] => 3,9,1
    [31] => 3,9,0
    [32] => 4,3,76
    [33] => 4,3,6
    [34] => 4,3,1
    [35] => 4,3,0
    [36] => 4,5,76
    [37] => 4,5,6
    [38] => 4,5,1
    [39] => 4,5,0
    [40] => 4,7,76
    [41] => 4,7,6
    [42] => 4,7,1
    [43] => 4,7,0
    [44] => 4,9,76

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表