找出给定值属于数组的哪两个值


Find which two values of an array a given value is belongs

假设我有一个类似这样的数组:

$months = Array('3','6','12','15','18','21','24');

我有$n = 5,怎样才能找到$n在数组中呢?
元素也应该追加在3 &6之前,因为5在3之间;6

e.g.
$n = 5; then array will be
$months = Array('3','5','6','12','15','18','21','24');
$n = 7; then array will be
$months = Array('3','6','7','12','15','18','21','24');

我还需要根据$n

显示进度
 e.g.
 $n=3 then up to $3 color will get filled
 $n=5 then color will get filled up to middle of 3 & 5 

我已经在div &我需要相应地显示进度。

进度条示例http://awesomescreenshot.com/04937zko93

假设months数组最初排序,我们遍历该数组并找到插入$n的确切位置,将该数组划分为两部分,并将$n插入到切片的中间

for($pos = 0; $pos < count($months); $pos++) {
    if($months[$pos] > $n) {
        break;
    }
}
$end_part     = array_slice($months, $pos);
$first_part   = array_slice($months, 0, $pos);
$first_part[] = $n;
$months       = array_merge($first_part, $end_part);
$n = 7;
$months = Array('3','6','12','15','18','21','24');
$i = 0;
foreach ($months as $k => $v) {
    if ($n < $v) {
        $months = array_merge(array_slice($months, 0, $i), array("$n"), array_slice($months, $i, count($months)));
        break;
    }
    ++$i;
}
var_dump($months);

如何将值插入到数组的正确位置:

$months = [3, 6, 12, 15, 18, 21, 24];
$n = 5;
$idx = count(array_filter($months, function($val) use($n) {
    return $val < $n;
}));
array_splice($months, $idx, 0, [$n]);

这是如何计算进度条使用的进度,假设:

  1. 第一个值(本例中为3)为0%
  2. 最后一个值(24)为100%,
  3. 数组中的每个数字之间有相同的差异(在本例中为3)

$pct = ($n - min($months)) / (max($months) - min($months)) * 100;