递归计算笛卡尔乘积


递归计算笛卡尔乘积

如果使用 laravel 的话,直接使用 collectcrossJoin 方法也可以实现

代码如下


<?php
/**
 * 递归计算笛卡尔乘积
 *
 * Created by PhpStorm.
 * User: Alex
 * Date: 2020/3/5
 * Time: 20:35
 */

namespace App\Handlers;


class CarteSianHandler
{
    /**
     * 保存结果
     *
     * @var array
     */
    public $products = [];

    /**
     * 计算笛卡尔乘积的结果
     *
     * @param array $params
     * @param array $temporary
     */
    public function carteSian(array $params, array $temporary = [])
    {
        foreach (array_shift($params) as $param) {
            array_push($temporary, $param);
            $params ? $this->carteSian($params, $temporary) : array_push($this->products, $temporary);
            array_pop($temporary);
        }
    }

}

使用


$params = [
    ['颜色_黑色', '颜色_白色', '颜色_咖啡色'],
    ['尺寸_S', '尺寸_M', '尺寸_L'],
    ['材质_羽绒', '材质_鹅绒']
];

$cartSian = new CarteSian();
$cartSian->carteSian($params);

print_r($cartSian->products);

返回结果


array:18 [
  0 => array:3 [
    0 => "颜色_黑色"
    1 => "尺寸_S"
    2 => "材质_羽绒"
  ]
  1 => array:3 [
    0 => "颜色_黑色"
    1 => "尺寸_S"
    2 => "材质_鹅绒"
  ]
  2 => array:3 [
    0 => "颜色_黑色"
    1 => "尺寸_M"
    2 => "材质_羽绒"
  ]
  3 => array:3 [
    0 => "颜色_黑色"
    1 => "尺寸_M"
    2 => "材质_鹅绒"
  ]
  4 => array:3 [
    0 => "颜色_黑色"
    1 => "尺寸_L"
    2 => "材质_羽绒"
  ]
  5 => array:3 [
    0 => "颜色_黑色"
    1 => "尺寸_L"
    2 => "材质_鹅绒"
  ]
  6 => array:3 [
    0 => "颜色_白色"
    1 => "尺寸_S"
    2 => "材质_羽绒"
  ]
  7 => array:3 [
    0 => "颜色_白色"
    1 => "尺寸_S"
    2 => "材质_鹅绒"
  ]
  8 => array:3 [
    0 => "颜色_白色"
    1 => "尺寸_M"
    2 => "材质_羽绒"
  ]
  9 => array:3 [
    0 => "颜色_白色"
    1 => "尺寸_M"
    2 => "材质_鹅绒"
  ]
  10 => array:3 [
    0 => "颜色_白色"
    1 => "尺寸_L"
    2 => "材质_羽绒"
  ]
  11 => array:3 [
    0 => "颜色_白色"
    1 => "尺寸_L"
    2 => "材质_鹅绒"
  ]
  12 => array:3 [
    0 => "颜色_咖啡色"
    1 => "尺寸_S"
    2 => "材质_羽绒"
  ]
  13 => array:3 [
    0 => "颜色_咖啡色"
    1 => "尺寸_S"
    2 => "材质_鹅绒"
  ]
  14 => array:3 [
    0 => "颜色_咖啡色"
    1 => "尺寸_M"
    2 => "材质_羽绒"
  ]
  15 => array:3 [
    0 => "颜色_咖啡色"
    1 => "尺寸_M"
    2 => "材质_鹅绒"
  ]
  16 => array:3 [
    0 => "颜色_咖啡色"
    1 => "尺寸_L"
    2 => "材质_羽绒"
  ]
  17 => array:3 [
    0 => "颜色_咖啡色"
    1 => "尺寸_L"
    2 => "材质_鹅绒"
  ]
]

文章作者: Alex
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Alex !
评论
  目录