繁体   English   中英

PHP数组键组合与元素的总和

[英]php Array key combination with sum of elements

Input:


  Array
(
[2] => 1
[7] => 1
[8] => 1
[9] => 2
)


 Output
  eg:
  [2] => 1
  [7] => 1
  [8] => 1
  [9] => 2
  [2_7] => 2 (sum of sf_2 and sf_7)

类似于下一个给定数组的所有可能组合,例如2_7_8(键)等...基本上是给定数组元素的组合...

不要以为有办法...您需要用_分割键,然后将所有[sf_$k[$i]]求和,其中$k是分割键, $i大于0 (以免尝试获取sf_sf

本质上...您将基本数组$base添加到结果数组$result直到不再更改

$base = array( 2 => 1, 7 => 1, 8 => 1, 9 => 2 );
$results = $base;
$changed = true;
while($changed) {
    $changed = false;
    foreach($results as $id => $sum) {
        // which elements are included already?
        $contained = explode('_', $id);        
        foreach($base as $num => $value) {
            if(!in_array((string)$num, $contained)) {  
                // if current is not included, add
                $newid = array_merge($contained, [$num]);
                sort($newid); // optional, unless name must be sorted
                if(!isset($results[implode('_', $newid)])) {
                    // only add, if we don't already know that new element.
                    $results[implode('_', $newid)] = $sum + $value;
                    // set changed to true, so that another pass is made
                    $changed = true;
                }
            }
        }
    }
}

这绝对不是最好或最有效的方法,但是它很简单并且有效。

如果不需要对键进行排序,则$results[$id.'_'.$num] = $sum + $value就足够了,而不是$newid创建,排序和内$newid

更新

如果基本数组具有n元素,则结果包含2 n元素的幂。 如果n足够大,我的幼稚实现将需要一些时间。

在这种情况下,更好的解决方案是:

$base = array( 2 => 1, 7 => 1, 8 => 1, 9 => 2 );
$sums = array();
$names = array();
$max = pow(2,count($base));
for($n=1; $n<$max; $n++)  {
    $sums[$n] = 0;
    $names[$n] = '';
    foreach(array_keys($base) as $index => $number) {
         $sums[$n] += ($n & pow(2,$index)) ? $base[$number] : 0;
         $names[$n] .= ($n & pow(2,$index)) ? '_'.$number : '';
    }
    $names[$n] = substr($names[$n], 1);
}
$result = array_combine($names, $sums);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM