可能重复:
MYSQL PHP-获取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'];
}
代码从用户名CCD_ 1获取float,从数据库中的表获取float并将其添加到数组中。
我怎么知道数组中的哪些浮点值接近$float
?
// 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));