在mysqli数组中查找最接近的值

时间:2018-06-07 21:08:06

标签: php sorting

在我的应用中,用户可以输入一个数字进行定价,根据输入,数据库将返回一个价格相同的计划。如果没有与用户输入相对应的数字/价格,我希望程序找到具有最近值的计划。我怎样才能找到最近的"在大海捞针中的价值?

Examples :
User inputs : $14, Returns the 15$ plan
User inputs : $20, Returns the 15$ plan
User inputs : 25$. Returns the 30$ plan
Etc...

这就是我所拥有的:

//Create pricing for each plan
$getplansql = "SELECT SUM(`Distributor Net Price`) AS dnetprice FROM `services` wspn
 WHERE wspn.planName = '$planname_num[$pn]' AND wspn.planLevel = '$planlevels_num[$pl]'";
 $resultplans = $conn->query($getplansql);

 while($plan = mysqli_fetch_assoc($resultplans)) {// output data of each row

  $inhousepricing = ($plan['dnetprice'] * 0.15) + ($plan['dnetprice']);
   $finalpricing = round($inhousepricing);

     if($planprice == $finalpricing) {//found matching row// there's a plan with that price
      //put plan info in array            
                        $planArray = array(
                          'planName' => $plan['name'],
                          'planPrice' => $finalpricing,
                          'planDescription' => $plan['description']
                        );
    break;//stop statement and only get the first plan//row found

    }else{//get the plan with the nearest value

     //put plan info in array  
    }

1 个答案:

答案 0 :(得分:1)

添加15%并在SQL查询中找到最接近的价格。

$getplansql = "name, description, dnetprice
               FROM (
                    SELECT planName AS name, planDescription AS description, ROUND(SUM(`Distributor Net Price`) * 1.15) AS dnetprice 
                    FROM `services` wspn
                    WHERE wspn.planName = '$planname_num[$pn]' AND wspn.planLevel = '$planlevels_num[$pl]'
                ) AS x
                ORDER BY ABS(dnetprice - $planprice)
                LIMIT 1";
$resultplans = $conn->query($getplansql);
$planArray = mysqli_fetch_assoc($resultplans);

这将只返回您想要的一行,因此您不需要while循环。