查找PHP数组元素的所有可能的唯一组合 [英] Find all possible unique combinations of elements of an array in PHP
问题描述
我所知道的涉及这个话题的几个问题(如这里),但没有人(至少是从我发现了什么)做我所需要的。
I’m aware of several questions covering this topic (e.g. here), but none of them (at least from what I found) do what I need.
说我有3个元素的数组 [1,2,3]
。我需要找出所有可能的唯一组合(不包括这样排列,就像这里 ),包括重复的元素的。这样的结果应该是:
Say I have an array of 3 elements [1, 2, 3]
. I need to find all the possible unique combinations (so excluding permutations, like here), including the ones of repeating elements. So the result should be:
[1]
[2]
[3]
[1, 1]
[1, 2]
[1, 3]
[2, 2]
[2, 3]
[3, 3]
[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 2, 3]
[1, 3, 3]
[2, 2, 2]
[2, 2, 3]
[2, 3, 3]
[3, 3, 3]
不包括像 [3,2,1]
或 [2,1,3]
,是的子集同样的事情, [1,2,3]
。
Excluding subsets like [3, 2, 1]
or [2, 1, 3]
, that are the same thing as [1, 2, 3]
.
我怎样才能做到这一点?
How can I achieve this?
推荐答案
使用快速的解决方案递归,可能不是最好的方式做到这一点,但它能够完成任务。
Fast solution using recursion, probably not the best way to do it, but it gets the job done.
<?php
$arr = array(1,2,3);
$result = array();
function combinations($arr, $level, &$result, $curr=array()) {
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);
}
// TEST
foreach ($result as $arr) {
echo join(" ", $arr) . '<br>';
}
?>
这篇关于查找PHP数组元素的所有可能的唯一组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!