获取三个数组的没有重复所有可能的组合 [英] Get all possible combinations of three arrays without duplicates

查看:138
本文介绍了获取三个数组的没有重复所有可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三只充满动态数组。这可能是因为只有一个或两个阵列具有数据

I've got three dynamically filled arrays. It's possible that only one or two arrays have data.

$array1 = array(
    [0] => 100GB
    [1] => 500GB
)

$array2 = array(
    [0] => black
    [1] => yellow
    [2] => green
)

$array1 = array(
    [0] => 2.5"
)

没有,我需要将它们组合成一个新的数组,包括所有可能的变化。

No I need to combine them into a new array that includes all possible variations

$variations = array(
    [0] => 100GB - black - 2.5"
    [1] => 100GB - yellow - 2.5"
    [2] => 100GB - green - 2.5"
    [3] => 500GB - black - 2.5"
    [4] => 500GB - yellow - 2.5"
    [5] => 500GB - green - 2.5"
)

到现在为止,我没有找到一个方法来做到这一点。
有人能帮帮我吗?

Until now I didn't find a way to do this. Can someone please help me?

感谢您提前

推荐答案

您可以轻松地与foreach循环实现这一点:

You can achieve this easily with foreach loops:

$array1 = array('100GB', '500GB');
$array2 = array('black', 'yellow', 'green');
$array3 = array('2.5');

$combinations = array();
foreach ($array1 as $i) {
  foreach ($array2 as $j) {
    foreach ($array3 as $k) {
      $combinations[] = $i.' - '.$j.' - '.$k;
    }
  }
}

echo implode("\n", $combinations);

编辑::要处理空数组,你可以使用此功能:

To handle empty arrays, you could use this function:

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;
}

这个功能是从采取这一的答案,所以要归功于作者。然后,您可以调用这个组合函数是这样的:

This function was taken from this answer, so credit goes to the author. You can then call this combinations function this way:

$array1 = array('100GB', '500GB');
$array2 = array();
$array3 = array('2.5');

$arrays = array_values(array_filter(array($array1, $array2, $array3)));
$combinations = combinations($arrays);

foreach ($combinations as &$combination) {
  $combination = implode(' - ', $combination);
}

echo implode("\n", $combinations);

此输出:

100GB - 2.5
500GB - 2.5

这篇关于获取三个数组的没有重复所有可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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