我有一个像下面这样的php数组 我想删除彼此太靠近的键,同时保留其中具有最大价值的键。
例如,在下面这三个条目中,我想保留165,并取消另外两个。
[163] => 13
[165] => 15
[166] => 14
同样,在下一对中,我想保留172并删除其他
[169] => 17
[170] => 17
[172] => 19
[174] => 14
我的数组看起来像这样:
Array(
[163] => 13
[165] => 15
[166] => 14
[169] => 17
[170] => 17
[172] => 19
[174] => 14
[206] => 10
[216] => 13
[218] => 15
[220] => 14
[228] => 15
[230] => 18
[231] => 16
[234] => 13
[237] => 10
[245] => 10
[248] => 12
[251] => 15
[254] => 13
[256] => 14
[260] => 15
[262] => 17
[264] => 17
[266] => 16
[268] => 14
[271] => 11
)
答案 0 :(得分:0)
可以做的一些事情已经证明了。
<?php
$a = array(
'163' => '13',
'165' => '15',
'166' => '14',
'169' => '17',
'170' => '17',
'172' => '19',
'174' => '14',
'206' => '10',
'216' => '13',
'218' => '15',
'220' => '14',
'228' => '15',
'230' => '18',
'231' => '16',
'234' => '13',
'237' => '10',
'245' => '10',
'248' => '12',
'251' => '15',
'254' => '13',
'256' => '14',
'260' => '15',
'262' => '17',
'264' => '17',
'266' => '16',
'268' => '14',
'271' => '11'
);
// arsort( $a ); // sort by value desc
krsort( $a ); // sort by key desc
echo "startet with … ";
print_r( $a );
$d = 0.05; //distance of 5%
$m = false; //flag for first key unset
foreach( $a as $k => $v ) {
if ( $m === false) { // first key will be max one
$m = $k;
}
else if( ($m - $k) < ($d * $m) ) { //comparison for range = $r = $d*$m; //set absolute range for dropping elms
unset( $a[$k] );//drop an entry
} else {
$m = $k;//set new/lower max for comparison
}
}
echo "endet up with … ";
print_r( $a );
?>
如果您有更精确的标准可以帮助您进行所需的选择。