根据最高分从数组中查找前10条记录


Find the top 10 records from an array on the basis of highest score

我无法弄清楚如何在使用php的最高分计算的基础上从数组中获取前10条记录。我从表中取出记录,执行计算并将结果存储在一个名为score的数组中,并与查询字符串(array)的其余部分相关联,这样我就可以将该计算带入JSON。我的问题是我只需要携带得分最高的前10个记录。

    $gold=$_GET['gold_input'];
    $silver=$_GET['silver_input'];
    $bronze=$_GET['bronze_input'];
    $gdp_value=$_GET['gdp_checked'];

    $link = new mysqli('localhost', 'root', '','coa123cdb');
    $myArray = array();
    $query = "SELECT  * FROM  coa123cdb.Country";
    $result = mysqli_query($link, $query)
    or die("Error: ".mysqli_error($link));
    $row_cnt = $result->num_rows;
    if ($result = $link->query($query)) {
    $tempArray = array();
    $score=array();
    $counter=0  ;
    while($row=mysqli_fetch_assoc($result)){
      $tempArray['country_name'] = $row['country_name'];
      $tempArray['gdp']=$row['gdp'];
      $tempArray['population']=$row['population'];
      $tempArray['gold']=$row['gold'];
      $tempArray['silver']=$row['silver'];
      $tempArray['bronze']=$row['bronze'];
                if($gdp_value==0)
            {
                        $score=($bronze*$tempArray['bronze'])+($silver*$tempArray['silver'])+($silver*$tempArray['gold']);
            }
            else
            {
            $score=($bronze*$tempArray[6]+$silver*$tempArray[5]+$silver*$tempArray[4])*$tempArray[1]/$tempArray[2]/10000;
            }
            $tempArray['score']=$score;
            $data[]=$tempArray;
            $counter++;
        }

       echo json_encode($data);
}
$result->close();
$link->close();

请建议我应该做什么,以便只通过前10个记录从数组到JSON对象。

首先,创建复杂的MySQL查询是更好的主意。

与返回所有结果和php计算的成本相比,MySQL的计算分数将几乎是免费的。

我建议创建sql查询+ "order by score limit 10"

SELECT  *,CASE gdp
WHEN 0 THEN bronze*silver
ELSE bronze*silver / 1000
END as score FROM coa123cdb.Country order by score desc limit 0,10

该代码用于在分数计算类型之间切换

CASE gdp
WHEN 0 THEN bronze*silver
ELSE bronze*silver / 1000
END

我希望我已经正确地理解了你,我认为最好的解决方案是排序你的数组并取前10个值。

对数组进行排序有很多函数。因为我懒得去学习它们,所以我更喜欢usort(),它让我完全控制正在做的事情。您可以按"得分"字段排序。也许有人会找到一个更好的函数。

获取前10个元素,可以使用简单的for循环。

如果您不希望对源数组进行排序,您可以随时复制它。

你必须先排序你的数组然后…限制获取记录试试这样写

  ---- your code above it ---
        $tempArray['score']=$score;
        $data[]=$tempArray;
        foreach($data as $value)
        {
           $score[]  = $value['score']
        }
        array_multisort($score, SORT_DESC,$data);
        $i = 0;
        $newArray = array();
        foreach($data as $value)
        {
            if($i < 10)
            {
                $newArray[] = $value;
            }
            $i++;
        }  

  --- code below----------  

$newArray将包含所需的数组…

你可以阅读更多关于array_multisort()

希望对你有所帮助

由于ORDER BY...LIMIT方法更有效,我将采用该方法。
请参阅代码内的注释以获得简短的解释。

/* Initialize variables */
$gold      = $_GET["gold_input"];
$silver    = $_GET["silver_input"];
$bronze    = $_GET["bronze_input"];
$gdp_value = $_GET["gdp_checked"];
$data = array();
/* Construct the query based on user input.
   The query should calculate the 'score' (taking '$gdp_value' into account)
   and then return the 10 highest scoring entries.
   The returned columns include all columns present in the 'Country' table
   plus an extra column named 'score' (which contains the calculated score).*/
$scoreFormula = ($gdp_value == 0)
        ? "((" . $bronze . " * bronze) + (" . $silver . " * silver) + (" . $gold . " * gold))";
        : "(((" . $bronze . " * bronze) + (" . $silver . " * silver) + (" . $gold . " * gold)) * (gdp / (population * 10000)))";
$query = "SELECT Country.*, " . $scoreFormula . " AS score
            FROM Country
            ORBER BY score DESC
            LIMIT 10";
/* Connect to the DB and execute the query */
$link = new mysqli("localhost", "root", "", "coa123cdb");
$result = mysqli_query($link, $query)
    or die("Error: " . mysqli_error($link));
/* Put the results into the '$data' array */
$row_cnt = $result->num_rows;
forEach ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}
/* Release resources */
$result->close();
$link->close();
/* Return the data */
echo(json_encode($data));

注意:
该代码仅用于说明目的。将未经过滤的用户输入放入SQL语句中总是一个坏主意。您应该使用预处理语句