get获取最接近其他浮点数的浮点数

时间:2012-07-19 14:37:01

标签: php mysql floating-point

  

可能重复:
  MYSQL PHP - get float LIKE $float

我有来自数据库的浮动。这是我的代码:

$float = $_GET['float'];
$requst = mysql_query("SELECT * FROM floats WHERE float LIKE'$float.%%%%%%%' AND float2 LIKE'$float2.%%%%%%%'");
while ($r = mysql_fetch_array($requst)) {

    $array[] = $r['float'];

}

代码从用户名$float获取浮动并从数据库中的表中浮动并将其添加到数组中。

我怎么知道数组中的浮点数接近$float

1 个答案:

答案 0 :(得分:0)

// Lets cast provided float to float type to prevent sql injections
$float = (float) $_GET['float'];
$requst = mysql_query("SELECT * FROM floats WHERE float LIKE'$float.%%%%%%%' AND float2 LIKE'$float2.%%%%%%%'");
$array = array();
while ($r = mysql_fetch_array($requst)) {
    // Lets store an array of differences between the provided float
    // and db floats, indexed by db float value
    $array[$r['float']] = abs($r['float'] - $float);
}
// Now lets sort the array by values(differences)
// keeping the keys intact
asort($array);
// The first key of the resulting array is the closest float to the provided float
$closest = array_pop(array_keys($array));
相关问题