【问题标题】:Get all possible combinations of three arrays without duplicates获取三个数组的所有可能组合而不重复
【发布时间】:2014-06-29 18:20:08
【问题描述】:

我有三个动态填充的数组。可能只有一两个数组有数据。

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

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

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

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

$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"
)

直到现在我还没有找到一种方法来做到这一点。 有人可以帮帮我吗?

提前谢谢你

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    您可以使用 foreach 循环轻松实现此目的:

    $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);
    

    编辑:要处理空数组,你可以使用这个函数:

    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 答案,因此归功于作者。然后你可以这样调用这个combinations函数:

    $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
    

    【讨论】:

    • 嗨,谢谢你,这部分解决了。问题是,如果没有 array3,则 $result 为空。我怎样才能避免这种情况?
    • 谢谢,那太好了!
    • 或许你也可以关注这里stackoverflow.com/questions/24499295/…
    【解决方案2】:

    您只需要使用嵌套循环。在第一个数组上循环一次,在第二个数组上循环一次,在第三个数组上循环一次,然后将每个数组中的项连接起来,并将结果推送到一个新数组中。

    【讨论】:

    • 嗨,你能用示例代码展示一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2018-06-17
    相关资源
    最近更新 更多