2013-02-17 85 views

回答

1

的另一种方法,使用具有差异的中间阵列:

$diff = array(); 

foreach($array as $n)  
    $diff[$n] = abs($x - $n); // key = number, value = difference 

// get the key that contains the smallest difference 
$closest = array_search(min($diff), $diff); 
+0

谢谢你的回复! – spm 2013-02-17 03:42:26

0
$min = 0; 
foreach ($array AS $i => $v) { 
    if (abs($array[$min] - $x) > abs($v - $x)) 
    $min = $i; 
    // you can optimize this with : 
    if ($v == $x) 
    break; 
} 
$closest = $array[$min]; 

类似的东西应该工作。

+0

感谢您的回复! – spm 2013-02-17 03:39:48

相关问题