我有一个数字数组:
var IP_array = [];
var starting, ending;
client.zrevrangebyscore(['ipaddress','+inf','-inf'],function(err,res){
IP_array.push(res);
});
starting = IP_array.indexOf('127.0.0.1');//staring IP range
ending = IP_array.indexOf('129.32.21.180');// ending IP range
console.log(IP_array.slice(starting, ending));
该命令没有任何意义。如果给定的数字是1、2和3,那么我希望收到此结果:
$numbers = array(1,2,3);
我该如何实现?
答案 0 :(得分:2)
您可以使用以下递归函数:
function powerSet($arr) {
if (!$arr) return array([]);
$firstElement = array_shift($arr);
$recursionCombination = comb($arr);
$currentResult = [];
foreach($recursionCombination as $comb) {
$currentResult[] = array_merge($comb, [$firstElement]);
}
return array_merge($currentResult, $recursionCombination );
}
现在print_r(powerSet([1,2,3]));
将为您提供所有这些选项作为数组。
使用空数组的添加选项作为powerSet编辑
答案 1 :(得分:0)
部分解决:
PHP: How to get all possible combinations of 1D array?
然后添加了我自己的函数进行清理:
function clean_depth_picker(&$result) {
$results = array();
foreach($result as $value) {
if ( substr_count($value, " ") == 0 ) {
$results[] = $value;
} else {
$arr = explode(" ", $value);
sort($arr);
$key = implode(" ", $arr);
if ( !in_array($key, $results) )
$results[] = $key;
}
}
$result = $results;
}
答案 2 :(得分:0)
可能是我在旧的SO帖子或Github要点上找到的。
<?php
function uniqueCombination($in, $minLength = 1, $max = 2000) {
$count = count($in);
$members = pow(2, $count);
$return = array();
for($i = 0; $i < $members; $i ++) {
$b = sprintf("%0" . $count . "b", $i);
$out = array();
for($j = 0; $j < $count; $j ++) {
$b{$j} == '1' and $out[] = $in[$j];
}
count($out) >= $minLength && count($out) <= $max and $return[] = $out;
}
return $return;
}
$numbers = array(1,2,3);
$return = uniqueCombination($numbers);
sort($return);
print_r(array_map(function($v){ return implode(" ", $v); }, $return));
?>
输出:
Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 1 2
[4] => 1 3
[5] => 2 3
[6] => 1 2 3
)