我想计算一个数组中具有几个数字的特定数字游侠。
在我的数组中,我有以下数字:
array(3500,3600,3700,3800,5000,5100);
现在我需要数字范围,输出将是:
1: 3500-3800
2: 5000-5100
任何人都知道实现这一目标的最佳途径是什么?
答案 0 :(得分:0)
只是为了好玩而实施,认为它可能以一种优雅的方式完成,但却想不到比这更好的东西:(这很难看)
$data = array(3500,3600,3700,3800,5000,5100);
sort($data);
$threshold = 100;
$result = array_reduce($data, function($result, $current) use($threshold) {
end($result);
$key = key($result);
if ($key === null) {
$result[] = array($current, $current);
} elseif (!isset($result[$key][1]) || $result[$key][1] + $threshold >= $current) {
$result[$key][1] = $current;
} else {
$result[] = array($current, $current);
}
return $result;
}, array());
var_dump($result);
第二次尝试:
$data = array(3500,3600,3700,3800,5000,5100);
sort($data);
$threshold = 100;
$result = array_chunk(
array_reduce($data, function($result, $current) use($threshold) {
$last = end($result);
if ($last !== false && $last + $threshold >= $current) {
$result[count($result) - 1] = $current;
} else {
$result[] = $current;
$result[] = $current;
}
return $result;
}, array()),
2
);
var_dump($result);