【问题标题】:Find unique (not repeating) combination php查找唯一(不重复)组合php
【发布时间】:2018-05-17 08:43:38
【问题描述】:

我在这里遇到一个技术问题,我有一个数组[PER_DAY, PER_SIZE, PER_TYPE],我想在不重复元素的情况下找到所有项目的组合,结果应该是

    [PER_DAY]
    [PER_SIZE]
    [PER_TYPE]
    [PER_DAY, PER_SIZE]
    [PER_DAY, PER_TYPE]
    [PER_SIZE, PER_TYPE]
    [PER_DAY, PER_SIZE, PER_TYPE]

这段代码重复相同的值,所以结果太多了。

$arr = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
$result = [];

function combinations($arr, $level, &$result, $curr=[]) {
    for($i = 0; $i < count($arr); $i++) {
        $new = array_merge($curr, array($arr[$i]));
        if($level == 1) {
            sort($new);
            if (!in_array($new, $result)) {
                $result[] = $new;          
            }
        } else {
            combinations($arr, $level - 1, $result, $new);
        }
    }
}
for ($i = 0; $i<count($arr); $i++) {
    combinations($arr, $i+1, $result);
}

这个问题可能重复,但我找不到类似的例子,谢谢。

【问题讨论】:

标签: php algorithm combinations


【解决方案1】:
   function pc_array_power_set($array) {
    // initialize by adding the empty set
    $results = array(array( ));

    foreach ($array as $element)
        foreach ($results as $combination)
            array_push($results, array_merge(array($element), $combination));

    return array_filter($results);
}
    $set = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
    $power_set = pc_array_power_set($set);
    echo '<pre>';
    print_r($power_set);

您已经从数组中进行组合,将帮助您:-PHP array combinations

【讨论】:

  • 为什么我们需要定义$max,在我的例子中,它应该是$in的长度吧?
  • 你得到答案了吗??
猜你喜欢
  • 2013-03-15
  • 2013-04-25
  • 1970-01-01
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 2015-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多