如何在 PHP 中生成多个数组中的所有项目组合 [英] How to generate in PHP all combinations of items in multiple arrays

查看:23
本文介绍了如何在 PHP 中生成多个数组中的所有项目组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在多个数组中查找所有项目组合.数组的数量是随机的(可以是 2、3、4、5...).每个数组的元素个数也是随机的……

I'im trying to find all combinations of items in several arrays. The number of arrays is random (this can be 2, 3, 4, 5...). The number of elements in each array is random too...

例如,我有 3 个数组:

For exemple, I have the 3 arrays :

$arrayA = array('A1','A2','A3');
$arrayB = array('B1','B2','B3');
$arrayC = array('C1','C2');

我想生成一个包含 3 x 3 x 2 = 18 个组合的数组:

I would like to generate an array with 3 x 3 x 2 = 18 combinations :

  • A1、B1、C1
  • A1、B1、C2
  • A1、B2、C1
  • A1、B2、C2
  • A1、B3、C1
  • A1、B3、C2
  • A2、B1、C1
  • A2、B1、C2...

问题是创建一个具有可变数量源数组的函数...

The problem is to create a function with a variable number of source arrays...

推荐答案

这里是递归解决方案:

function combinations($arrays, $i = 0) {
    if (!isset($arrays[$i])) {
        return array();
    }
    if ($i == count($arrays) - 1) {
        return $arrays[$i];
    }

    // get combinations from subsequent arrays
    $tmp = combinations($arrays, $i + 1);

    $result = array();

    // concat each array from tmp with each element from $arrays[$i]
    foreach ($arrays[$i] as $v) {
        foreach ($tmp as $t) {
            $result[] = is_array($t) ? 
                array_merge(array($v), $t) :
                array($v, $t);
        }
    }

    return $result;
}

print_r(
    combinations(
        array(
            array('A1','A2','A3'), 
            array('B1','B2','B3'), 
            array('C1','C2')
        )
    )
);

这篇关于如何在 PHP 中生成多个数组中的所有项目组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆